2011-04-14 28 views
0

我有這樣的形式:如何在用戶未登錄時通過此代碼?

<%= form_for current_user.relationships.build(:followed_id => @profile.user.id) do |f| %> 
    <div><%= f.hidden_field :followed_id %></div> 
    <div class="follow_button"><%= f.submit "Follow" %></div> 
<% end %> 

,並因爲它使用current_user它拋出時未登錄的用戶我想一個錯誤非登錄用戶才能夠看到按鈕,但它失敗:

before_filter :authenticate

點擊時。我應該如何更改表單代碼?好像我可能需要將relationship.build調用移動到控制器?或者如何讓我的應用程序控制器中的按鈕調用authenticate方法?

+0

您想給用戶一個表單填寫,使他們能夠再失敗,被迫登錄並丟失他們輸入的數據?看起來像一個非常糟糕的用戶體驗。 – 2011-04-14 00:25:23

+0

這不是一個完整的表格。這只是一個跟隨的按鈕。我希望用戶在登錄後查看可用的功能... – 2011-04-14 00:37:51

回答

0

我不認爲它很好的做法稱之爲User.new如前所述。您可以在視圖始終區分:

<% if current_user %> 
    Form goes here 
<% else %> 
    <div class="follow_button">Log in to follow</div> 
<% end %> 

(或作第二個按鈕,導致登入)

0

您可以隨時向系統中添加一個通用的「註銷」用戶,默認情況下當沒有會話時,然後在處理點擊時檢查該用戶。這會給你一種你想要的靈活性,而不會讓你的模型變糟。

0

怎麼樣:

<% user = current_user || User.new %> 

    <%= form_for user.relationships.build(:followed_id => @profile.user.id) do |f| > <div> 
     <%= f.hidden_field :followed_id %></div> <div class="follow_button"> 
     <%= f.submit "Follow" %> 
    </div> 
    <% end %> 

我幾乎在我的應用程序相同的關係,似乎工作:

User.new.friendships.build(:friend_id => 4) # => 
<Friendship id: nil, user_id: 0, friend_id: 4, approved: false, canceled: false, marked_as_deleted: false, created_at: nil, updated_at: nil> 
相關問題