我正在尝试更改Dispute
对象的状态:
class Dispute < ActiveRecord::Base
STATUSES = %w(open finished).freeze
STATUSES.each do |method|
define_method "#{method}?" do
status == method
end
end
def self.statuses
STATUSES
end
end
在create
和update
方法中:
def create
Dispute.new
if params[:status] == 'Open'
dispute.status = dispute.statuses[0]
end
if dispute.save
redirect_to dispute_path(@dispute)
flash[:success] = 'Hooray'
else
flash[:error] = 'Error'
redirect_to :back
end
end
我处理了方法中的属性,但状态没有改变。使用回调而不是控制器更改模型中的状态是否更好?
答案 0 :(得分:0)
要更改状态,您只需执行
def create
Dispute.new
if params[:status] == 'Open'
dispute.status = dispute.statuses.open!
end
if dispute.save
redirect_to dispute_path(@dispute)
flash[:success] = 'Hooray'
else
flash[:error] = 'Error'
redirect_to :back
end
end
您可以访问http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html以获取有关列的更多帮助。