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

问题描述:

应用程序的用户必须激活那里的帐户才能编辑或删除条目。如果帐户处于活动状态,Rails将验证状态

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

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

我的控制器被称为activate-action将通过电子邮件发送给用户。

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设置城市城市,但rhis将无法正常工作。

为什么该条目未激活?每个人都能帮助我吗?

+0

你有阅读['state_machine'](文档https://github.com/pluginaweek/ state_machine)? –

+0

是的,这是问题所在。文件说,条目。状态我可以设置状态。但这不起作用 – amarradi

+0

是否有任何操作错误日志?或者在rails控制台中尝试使用该方法'@user.activate'并检查它是否工作或任何错误。我已经使用[state_machine](https://github.com/pluginaweek/state_machine)并遇见问题[#261](https://github.com/pluginaweek/state_machine/issues/261)和[#334]( https://github.com/pluginaweek/state_machine/issues/334)。解决方案是改变宝石,使用[state_machines-activerecord](https://github.com/state-machines/state_machines-activerecord)来代替。 – gaga5lala

一旦您设置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你。

如果您在轨控制台

# 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宝石的样品使用,state_machine帮助你管理数据模型的状态下工作,而不是控制器。

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

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

希望这会你:)

+0

你的答案@ gaga5lala是非常有帮助的。这很容易使用。我只有一线改变。 ' 'event:activate do ** transition:inactive =>:active ** end' – amarradi

+0

@amarradi oops,我没有注意到state_machine使用的语法错误。感谢提醒,我将其固定在我的答案! – gaga5lala

+0

这不是语法错误,但第一种方法不适用于我。为什么我的问题得到-1?我能做些什么更好? – amarradi