我正在尝试更改对象的状态:
1)通过用户单击/view/matchday/index.html.erb中的按钮:
<%= button_to "End Matchday", {:action => :end_matchday}, :class => "push-9" %>2)或者2天过去了。每次用户访问索引时,它都会运行end_of_matchday_check来查看这是否正确。
matchdays_controller.rb:
def index
@matchdays = Matchday.all
@current_matchday = Matchday.last
# Runs a check on the last matchday whether user can edit the matchday
end_of_matchday_check unless Matchday.all.empty?
end
def end_matchday
@current_matchday = Matchday.last
@current_matchday.update_attributes(:ended => true)
redirect_to matchdays_path
end
private
# Returns true if the last matchday has exceeded 2 days = the allowable editing priod.
def end_of_matchday_check
@current_matchday = Matchday.last
unless @current_matchday.ended?
@current_matchday.update_attributes(:ended => true) if @current_matchday.created_at + 2.days > Time.now
end
end然而,我一直遇到这个问题(开发日志):
WARNING: Can't mass-assign protected attributes: ended但是,如果我注释掉attr_accessible行或添加:ended到它,它将会工作。但是,每次我访问索引页面时,每当我创建一个新的matchday对象时,它都会将matchday.ended更改为true。
Matchday.rb:
attr_accessible :name, :best_of, :description你知道为什么会发生这种情况吗?
发布于 2011-03-25 20:00:20
def end_matchday
@current_matchday = Matchday.last
@current_matchday.ended = true
@current_matchday.save
redirect_to matchdays_path
end或
def end_matchday
@current_matchday = Matchday.last
@current_matchday.update_attribute( :ended, true )
redirect_to matchdays_path
end更新
好的。
你应该把所有的update_attributes(:ended => true)移动到update_attribute(:ended, true)或@object.ended = true; @object.save
摘要
def index
@matchdays = Matchday.all
@current_matchday = Matchday.last
# Runs a check on the last matchday whether user can edit the matchday
end_of_matchday_check unless Matchday.all.empty?
end
def end_matchday
@current_matchday = Matchday.last
@current_matchday.update_attribute(:ended, true)
redirect_to matchdays_path
end
private
# Returns true if the last matchday has exceeded 2 days = the allowable editing priod.
def end_of_matchday_check
@current_matchday = Matchday.last
unless @current_matchday.ended?
@current_matchday.update_attribute(:ended, true) if @current_matchday.created_at + 2.days > Time.now
end
end发布于 2011-03-25 20:32:23
我终于想通了。我的
@current_matchday.created_at + 2.days > Time.now 逻辑是错误的。它应该是
@current_matchday.created_at + 2.days < Time.now <而非>。当前时间应该超过2天,然后它会将属性更改为true,并且在2天内不会更改它。
更新
我首先应用了flOOr的解决方案
@current_matchday.update_attributes(:ended => true)至
@current_matchday.update_attribute(:ended, true)在应用了他的解决方案之后,弹出了另一个解决方案,我错误地写下了它,认为这就是解决方案。
很抱歉混淆了flOOr,再次感谢,非常感谢:)
https://stackoverflow.com/questions/5432072
复制相似问题