【发布时间】:2015-07-01 22:27:52
【问题描述】:
我对 ruby on rails 比较陌生。我建立了一种叫做友谊的关系,它具有以下属性:
user_id, friend_id, state
在我的friendship.rb模型文件中,我创建了一个相反的方法来帮助我获得反向友谊:
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
在我的视图文件中,我有:
<h1> Requests Ive sent: </h1>
<%@sent_friendships.each do |x|%>
<%=x.opposite%><br>
<%=x.opposite.inspect%>
<%end%>
注意:@sent_friendships 在我的控制器中定义为:@sent_friendships=current_user.friendships.where(state:'pending');
查看输出:
x.对面:
#<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">]>
但是在调用 x.opposite.inspect 之后,我如何才能访问特定属性,例如状态?如果我尝试 x.opposite.state 我得到错误:
undefined method `state' for #<Friendship::ActiveRecord_Relation:0x007fd8a3f612f0>
我很困惑?调用inspect方法后清楚.state是一个属性吗?请帮忙?!
【问题讨论】:
-
你能写下这个查询的结果吗 -> @sent_friendships=current_user.friendships
标签: ruby-on-rails object ruby-on-rails-4 activerecord model