Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 需要来自rails连接表的数据,有很多:通过_Ruby On Rails_Associations_Has Many Through_Has Many - Fatal编程技术网

Ruby on rails 需要来自rails连接表的数据,有很多:通过

Ruby on rails 需要来自rails连接表的数据,有很多:通过,ruby-on-rails,associations,has-many-through,has-many,Ruby On Rails,Associations,Has Many Through,Has Many,我有3个表-用户、事物和追随者。用户可以通过下表跟踪内容,将用户id与内容id关联。这意味着: class User has_many :things, :through => :follows end class Thing has_many :users, :through => :follows end class Follow belongs_to :users belongs_to :things end 所以我可以毫无问题地检索thing.users

我有3个表-用户、事物和追随者。用户可以通过下表跟踪内容,将
用户id
内容id
关联。这意味着:

class User
  has_many :things, :through => :follows
end

class Thing
  has_many :users, :through => :follows
end

class Follow
  belongs_to :users
  belongs_to :things
end
所以我可以毫无问题地检索thing.users。我的问题是,如果在下表中,我有一个名为“relation”的列,那么我可以将跟随者设置为“admin”,我希望能够访问该关系。因此,在一个循环中,我可以做如下操作:

<% things.users.each do |user| %>
  <%= user.relation %>
<% end %>
<% things.follows.each do |follow| %>
  <%= follow.relation %>
  <%= follow.user %>
<% end %>


是否有方法将关系包含到原始用户对象中?我已经尝试了
:select=>“follow.relation”
,但它似乎没有加入属性。

要做到这一点,您需要在has\u many中使用一些SQL。像这样的事情应该很有希望奏效。
有许多:用户,:通过=>:follows,:select=>'users.*,follows.is_admin as is_follow_admin'

然后在循环中,您应该可以访问
user.is\u follow\u admin

您可以执行以下操作:

<% things.users.each do |user| %>
  <%= user.relation %>
<% end %>
<% things.follows.each do |follow| %>
  <%= follow.relation %>
  <%= follow.user %>
<% end %>

对于使用rails 4的用户,不推荐使用:order、:select等。现在需要指定如下内容:

has_many :users, -> { select 'users.*, follows.is_admin as is_follow_admin' }, :through => :follows

把一段关系命名为“关系”真是个坏主意。。。这可能会破坏一些ruby的内部结构,您将得到意想不到的行为!好的,谢谢。假设该列名为“is_admin”,并且有一种布尔类型。它确实有效,基本上就是我以前尝试过的。我的问题是,在命令行上执行此操作时,SQL转储不会在任何地方显示is_admin属性。。它只显示以下对象。非常感谢。Rails4已弃用:选择“我认为”。这是如何实现的?我正在使用rails 4,这种格式很有效
有很多:用户,>{select('users.*,members.role as member\u role')},通过::members
@Matt Gaidica,您应该将其添加到您的用户模型中(使属性可访问)def is\u follow\u admin属性['is\u follow\u admin']end