【问题标题】:Nested :has_many, :through attributes嵌套 :has_many, :through 属性
【发布时间】:2012-03-10 11:00:44
【问题描述】:

我正在使用 has_many :through 使用名为  list_items 的传递在两个模型之间创建关联:

user.rb:

  has_many :list_items
  has_many :wishes, :through => :list_items

wish.rb:

  has_many :list_items
  has_many :users, :through => :list_items

list_item.rb:

  belongs_to :user
  belongs_to :wish

这很好用,但是, list_items 具有模型  wishes 的其他属性,我想根据来自  users 的标准访问这些属性(确切地说是 current_user )。我目前可以使用如下代码访问此属性:

wishes_controller.rb:

  @wishes = current_user.wishes

index.html.haml:

 -wish.list_items.each do |list_item|
    -if list_item.user_id == current_user.id
        =list_item.list_position

这很好用,但是,我敢打赌,有一种更优雅的方法可以做到这一点,能够像 wishes.list_position 一样访问它(这将根据 current_user id 提取适当的 list_position)。我查看了 herehere(以及许多其他地方),但我无法将这些概念转化为我的项目。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 has-many-through


    【解决方案1】:

    查看Need data from rails join table, has_many :through

    试试这个。
    用户.rb:

    has_many :wishes, :through => :list_items, :select => 'wishes.*, list_items.list_position as list_position'

    这给了你:

    - @wishes.each do |wish|
      = wish.list_position
    

    【讨论】:

    • 工作完美!所以这段代码会选择 list_position (list_items.list_position) 并为每个愿望创建“list_position”(作为 list_position)?
    • 是的,您可以随意调用它,但除非您的愿望对象上也有 list_position 属性,否则应该可以解决问题
    猜你喜欢
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多