访问控制让我绊倒
好吧,我正处于我的红宝石职业生涯的那个阶段,这应该会让我绊倒。
我有一个名为 distribution.rb
的模型,其中有以下 protected 方法:
def update_email_sent_on_date
if self.send_to_changed?
self.date_email_delivered = DateTime.now
end
end
然后我从我的控制器调用此方法:
distribution.update_email_sent_on_date
但是,我收到此错误:
NoMethodError (protected method `update_email_sent_on_date' called for #<EmailDistribution:0x131a1be90>):
< code>distribution 对象确实是一个 EmailDistribution (定义该方法的 distribution 的子类)。我认为这会起作用。无论如何,我也尝试将该方法移动到子类 EmailDistribution
但没有成功。同样的错误消息。
我还想退一步说,我总体上想做的是存储更新分布模型中另一个字段的时间戳。如果有更简单的方法,请赐教。
ok, i'm about at that point in my ruby career where this should be tripping me up.
I have a model called distribution.rb
where I have the follwoing protected method:
def update_email_sent_on_date
if self.send_to_changed?
self.date_email_delivered = DateTime.now
end
end
I then call this method from my controller:
distribution.update_email_sent_on_date
however, I'm getting this error:
NoMethodError (protected method `update_email_sent_on_date' called for #<EmailDistribution:0x131a1be90>):
the distribution
object is indeed an EmailDistribution (a subclass of distribution where the method is defined). I thought this would work. In any case, I also tried moving the method to the subclass EmailDistribution
but no luck. Same error message.
I'd also like to step back and say that what I'm trying to do overall is store the timestamp of when another field in the distribution model is updated. If there's a simpler way, please enlighten me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您被绊倒了,因为当您实际上需要
private
声明时,您正在使用protected
声明。Ruby 中的
protected
术语在其他传统语言中的作用有所不同.恕我直言,这是一个稍微清晰的解释,来自 Russ Olsen 的Eloquent Ruby一书:
最后,值得注意的是,在 ruby 中,您始终可以调用私有或受保护的方法,无论它们是否可以使用
send
方法访问。因此,如果您手头紧要,只需要工作,您可以这样调用它,然后再担心private/protected
声明:阅读本文以获得更多更好的解释。。
I think you're getting tripped up because you are using the
protected
declaration when you actually want theprivate
declaration.The
protected
term in ruby acts differently in other conventional languages.This is a slightly clearer explanation IMHO, from the book Eloquent Ruby by Russ Olsen:
Lastly, it's good to note that in ruby you can always call private or protected methods regardless of whether they are accessible by using the
send
method. So if you were in a pinch and just needed to work you could just call it like this and then worry about theprivate/protected
declarations later:Read this for more a better explanation..