Reputation: 899
Hi I am trying to show the current users friend list / or the friends that might be pending, but i got an error like this one
NoMethodError in UserFriendships#index
undefined method `each' for nil:NilClass
this is what is was showing to give out the error
<% @user_friendships.each do |friendship| %>
This is my code in the controller
before_filter :authenticate_user!
def index
@user_friendship = current_user.user_friendships.all
end
this is my code in the index
<% @user_friendships.each do |friendship| %>
<% friend = friendship.friend %>
<div id="<%= dom_id(friendship) %>" class="friend now">
<div class="span1">
<%= link_to image_tag(friend.gravatar_url), profile_path(friend) %>
</div>
</div>
</div>
<% end %>
I have already defined the @user_friendship in my controller but it seems that its not working properly I am a bit new here and getting things together, but this error keeps me from going forward, if anybody can help me that would be great!
Upvotes: 0
Views: 493
Reputation: 2357
Rails cannot see your defined method user_friendships
on current_user, hence @user_friendship is nill.
For your use, you would need to only call id
directly on current_user
, like
@user_id = current_user.id
Then, you can search the database for the User with this particular id
@current_user = User.find(@user_id)
So, you can get any method this new @current_user, in your case;
def index
@user_friendship = @current_user.user_friendships.all
end
And proceed with the list
<% @user_friendships.each do |friendship| %>
Rails is an MVC framework, meaning Models, Views, and Controllers. The Models primarily, enables communication between the database (like MYSql) and the controllers. Views are basically what the users see (like HTML, CSS), they communicate and grasp needed data through the Controller. And the Controller does the most work. The Controller takes in requests from the user, points the request through a model to the database, and returns the result to the view. All these are done by the Controller with the help of the server. For further explanations on Rails MVC framework and MVC generally, please checkout these links
How are Model, View and Controller connected?
http://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/
http://www.codelearn.org/ruby-on-rails-tutorial/mvc-in-rails
http://blog.codinghorror.com/understanding-model-view-controller/
Upvotes: 1