1

I am relatively new with ruby on rails. I made a relationship called friendships, which has the following attributes:

user_id, friend_id, state

Inside my friendship.rb model file, i have created an opposite method to help me get inverse friendships:

class Friendship < ActiveRecord::Base

def opposite
    user = self.user_id;
    friend=self.friend_id;
    return Friendship.where(user_id:friend,friend_id:user);
  end

end

Inside my view file i have:

<h1> Requests Ive sent: </h1>
<%@sent_friendships.each do |x|%>
  <%=x.opposite%><br>
  <%=x.opposite.inspect%>
<%end%>

Note: @sent_friendships is defined in my controller as: @sent_friendships=current_user.friendships.where(state:'pending');

View Output:

x.opposite:

#<Friendship::ActiveRecord_Relation:0x007fd8abcf3498>

x.opposite.inspect:

#<ActiveRecord::Relation [#<Friendship id: 4, user_id: 3, friend_id: 1, created_at: "2015-07-01 21:42:21", updated_at: "2015-07-01 21:42:21", state: "requested">]>

But after calling x.opposite.inspect, how can i access specific attributes, for example just the state? If i try x.opposite.state i get the error:

undefined method `state' for #<Friendship::ActiveRecord_Relation:0x007fd8a3f612f0>

I am confused? It clear that .state is an attribute after calling the inspect method? Help please?!

1
  • could you write down the result of this query -> @sent_friendships=current_user.friendships Commented Jul 2, 2015 at 15:44

1 Answer 1

1

What you are returning from opposite using Active Record 'where' is an ActiveRecord::Relation which is an array like structure. So x.opposite.first.state should get what you want.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.