我正在尝试更改对象的状态:
1)用户点击/view/matchdays/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行或者添加:结束了它,它就会起作用。但是每次我访问索引页面时,每次创建新的matchday对象时,它都会将matchday.ended更改为true。
Matchday.rb:
attr_accessible :name, :best_of, :description
知道为什么会这样吗?
答案 0 :(得分:0)
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
<强> UPD 强>
确定。
您应该将所有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
答案 1 :(得分:0)
我终于明白了。我的
@current_matchday.created_at + 2.days > Time.now
逻辑错了。它应该是
@current_matchday.created_at + 2.days < Time.now
&LT;而不是&gt;。当前时间应该超过2天,然后将属性更改为true,并且不会在2天内更改。
<强>更新强>
我首先通过更改
来应用flOOr的解决方案 @current_matchday.update_attributes(:ended => true)
到
@current_matchday.update_attribute(:ended, true)
在应用他的解决方案后,另一个弹出,我写错误地认为它是解决方案。
对不起,混合flOOr再次感谢,非常感谢:)