【问题标题】:How to access Active Record Object Values ? Ruby on Rails如何访问 Active Record 对象值? Ruby on Rails
【发布时间】: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


【解决方案1】:

使用 Active Record 'where' 从对面返回的是 ActiveRecord::Relation,它是一个类似数组的结构。所以x.opposite.first.state 应该得到你想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    相关资源
    最近更新 更多