以多对多关系从连接中获取属性值

时间:2013-12-26 06:54:40

标签: ruby-on-rails ruby-on-rails-4 many-to-many jointable

User和“Link”之间存在多对多关系。

连接模型称为LinkAddress,除了保存其他两个模型的ID之外,还有一个名为address的属性 - 它在创建时收集的信息。

如何在请求方案中访问特定链接的地址属性,如下所示:User.first.links.first.address

模特:

class User < ActiveRecord::Base
  has_many :link_addresses, dependent: :destroy
  has_many :links, through: :link_addresses
  accepts_nested_attributes_for :link_addresses, allow_destroy: true
end

class LinkAddress < ActiveRecord::Base
  belongs_to :user
  belongs_to :link
end

class Link < ActiveRecord::Base
  has_many :link_addresses, dependent: :destroy
  has_many :users, through: :link_addresses
end

2 个答案:

答案 0 :(得分:2)

您可以通过User访问它,因为它是has_many ... :through关系:

User.first.link_addresses.first.address

或者,如果您想通过links,那么:

User.first.links.first.link_addresses.first.address

答案 1 :(得分:0)

SQL别名

我有这个问题:Rails Scoping For has_many :through To Access Extra Data

这是我得到的答案:

    #Images
    has_many :image_messages, :class_name => 'ImageMessage'
    has_many :images, -> { select("#{Image.table_name}.*, #{ImageMessage.table_name}.caption AS caption") }, :class_name => 'Image', :through => :image_messages, dependent: :destroy

这使用我在SQL Aliases(大约6:40左右)找到的this RailsCast。它允许我们调用@user.image.caption(即使.caption在联接模型中)


您的代码

对于您的查询,我会使用:

class User < ActiveRecord::Base
  has_many :link_addresses, dependent: :destroy
  has_many :links, -> { select("#{Link.table_name}.*, #{LinkAddress.table_name}.address AS address") }, through: :link_addresses

  accepts_nested_attributes_for :link_addresses, allow_destroy: true
end

这将允许您编写@user.links.first.address,并优雅地处理缺少address记录