如何更改方法的状态

时间:2017-05-18 01:06:50

标签: ruby-on-rails

我正在尝试更改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

createupdate方法中:

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

我处理了方法中的属性,但状态没有改变。使用回调而不是控制器更改模型中的状态是否更好?

1 个答案:

答案 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以获取有关列的更多帮助。