TABISH KHAN
TABISH KHAN

Reputation: 1623

How to access Active Record Object Values ? Ruby on Rails

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?!

Upvotes: 1

Views: 1453

Answers (1)

osman
osman

Reputation: 2459

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.

Upvotes: 1

Related Questions