Rails 如果帐户处于活动状态则验证状态

Rails validate state if account is active

应用程序的用户必须先激活该帐户才能编辑或删除条目。

如何将状态从不活动设置为活动? 我正在使用 pluginaweek 中的 state_machine 来设置状态。

state_machine initial: :inactive do
event :activate do
    state = 'active'
  end
end

我调用激活动作的控制器将通过电子邮件发送给用户。

def activate
@entry = Entry.find([:id])
if (check_email_link(@entry.exp_date))
  if @entry.save
    flash[:notice] = t("activate")
    redirect_to @entry
    else
      flash[:error] = t("already_activated")
      redirect_to @entry
  end 
else
  flash[:error] = t("timeout")
  redirect_to @entry.new
end

结束 文档说我可以通过 entry.state 设置 Städte,但 rhis 不起作用。

为什么条目没有激活?大家能帮帮我吗?

设置 state_machine 后,它会根据您的代码向 ActiveRecord(缩写 AR)模型添加一些方法。

例如:(只是演示代码,可能有错别字|||)

# setup state_machine for model Entry
class Entry < ActiveRecord::Base
  state_machine initial: :inactive do
    event :activate do
      transition :inactive => :active
    end
  end
end

然后state_machine设置方法activate给你。

如果您在 rails 控制台中操作

# Create an instance of Entry, you will see the attribute `state` value is "inactive" as your setting.
@entry = Entry.create
#=> {:id => 1, :state => "inactive"}

# Then use the method `activate` state_machine define for you according your setting. You will see `state` been changing to "active".
@entry.activate
#=> (sql log...)
#=> {:id => 1, :state => "active" }

这是 state_machine gem 的示例用法,state_machine 帮助您管理数据模型的状态,而不是控制器。

所以,您的代码可能是这样的:

class SomeController < ApplicationController
  def some_routes_that_activate_user
    # (some logic...)
    @entry.activate
  end
end

希望你能做到:)