How can I get this code to pass when the user is not logged in?
I have this form:
<%= form_for current_user.relationships.build(:followed_id => @profile.user.id) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
&l开发者_Python百科t;div class="follow_button"><%= f.submit "Follow" %></div>
<% end %>
and since it uses current_user
it throws an error when the user is not logged in. I want a non-logged in user to be able to see the button, but for it to fail:
before_filter :authenticate
when clicked. How should I change the form code? Seems like I may need to move the relationship.build call to the controller? Or how would I make the button call the authenticate
method in my application controller?
I don't think its good practise to call User.new as proposed before. You can always differentiate in your view:
<% if current_user %>
Form goes here
<% else %>
<div class="follow_button">Log in to follow</div>
<% end %>
(or make a second button that leads to sign-in)
You could always add a generic "logged out" user to the system, default to that when no session is present, and then check for that user when the click is handled. That'd give you the kind of flexibility you want without mucking up your model.
how about:
<% 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 %>
I have pretty much the same relations in my app and it seems to work:
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>
精彩评论