开发者

I'm having this problem: undefined method `each' for #<User:0xa8dc8b8>

19: <strong>URL</strong> <%= link_to user_path(@user),(@user)%><br />
20: 
21: <strong>Thoughts</strong> <%= @user.thoughts.count %>
22: <% @user.each do |user| %>
23: <li>
24:   <% if Friendship.are_friends(current_user, user) %>
25:     (you are friends)

It's throwing the error at line 22. I don't understand why. I'm simply just trying to do the loop for each friend.

EDIT:1

I'm actually trying to send a friendship request through a link in my social networks sidebar. Here is the code it missed out:

     <% @user.friendship.each do |user| %>
          <li>
<% if Friendship.are_friends(current_user, user) %>
  (you are friends)
<% elsif current_user != user %>
  (<%= link_to "request friendship", :controller => :friendship, :action => :req, :id => user.n开发者_C百科ame %>)
                <% end %>
                </li>
<% end %>

<h2>Your Friends</h2>
<ol>
<% @user.each do |friendship| %>
  <li><%= friendship.friend.name %>, <%= friendship.status %></li>
<% end %>
</ol>

I've tried adding user.friendship and it does render the page but there is no link to add friends.


@user is a single record (one user) -- you use .each to loop through an array of records, not a single record.

Maybe you meant something like @user.friends.each do |user|?


Firstly, you probably need to pluralise 'friendship'. If a user has_many :friendships, then your code should be @user.friendships.each

Secondly, @user.friendships.each will return Friendships, not Users. How are your models set up? Assuming you have a User model, and a Friendship model. The friendship model should look something like this:

class Friendship < ActiveRecord::Base
  #attributes should be :person_id, friend_id
  belongs_to :person, :class_name => "User"
  belongs_to :friend, :class_name => "User"
end

And the user model like this:

class User < ActiveRecord::Base
  has_many :friendships, :foreign_key => "person_id", :dependent => :destroy
  has_many :friends, :through => :friendships
end

In which case, you would want to use @user.friends.each instead of @user.friendships.each. The first will loop through an array of Users, the second will loop through Friendships.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜