2016-11-05 115 views
-1

應用程序的用戶必須激活那裏的帳戶才能編輯或刪除條目。如果帳戶處於活動狀態,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

回答

1

一旦您設置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

相關問題