State Machine Rails 4 没有回到初始状态

State Machine Rails 4 doesn't back to the initial state

我需要一些关于状态机的帮助,因为我正在使用 rails 4 我有一个名为 in_analysis 的初始状态,其他状态称为批准和拒绝,批准和拒绝的状态有效很好,我没有问题可以通过状态,但是我无法返回到称为 in_analysis 的初始状态,这是我的代码:

app/models/profile.rb

state_machine :state, :initial => :in_analysis do
 state :in_analysis, :approved, :rejected

 state :approved do
  validates :name, presence: true
 end

 event :approved do
  transition in_analysis: :approved
 end

 event :reject do
  transition in_analysis: :rejected
  transition approved: :rejected
 end
end

在我的控制器中我有这个:

  def update
   @profile.state = :in_analysis

   @profile = current_user.profile

  respond_to do |format|
   if @profile.update(profile_params)
    format.html { redirect_to edit_profile_path(@profile), notice:     t(:update, scope: [:messages, :controllers, :profiles, :successfully]) }
    format.json { render :show, status: :ok, location: edit_profile_path(@profile) }
   else
    format.html { render :edit }
    format.json { render json: @profile.errors, status: :unprocessable_entity }
  end
 end
end

所以我的目标是当配置文件更新时状态恢复到初始 "in_analysis" 但我不知道为什么不起作用,因为另一个状态运行良好。

感谢您的宝贵时间!问候 !

假设你的 state_machine 是正确的,你唯一可能做错的地方是

@profile.state = :in_analysis

@profile = current_user.profile

您将 state 分配给 :in_analysis 然后您实际上将 @profile 分配给从数据库中获取的旧 current_user.profile 因此您对 :in_analysis 的分配是丢弃。

你可以试试换两行:

@profile = current_user.profile
@profile.state = :in_analysis