嵌套:的has_many,:通过属性
问题描述:
我使用的has_many:嵌套:的has_many,:通过属性
user.rb:
has_many :list_items
has_many :wishes, :through => :list_items
wishe.rb通过使用直通称为 list_items
建立两个模型之间的关联:
has_many :list_items
has_many :users, :through => :list_items
list_item.rb:
belongs_to :user
belongs_to :wish
这很好用,但是, list_items
对于我想根据 users
(准确地说是 current_user
)的标准访问的型号 wishes
有附加属性。我可以用这样的代码目前访问该属性:
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)。我看过here和here(还有一些额外的地方),但我还没有能够将这些概念翻译成我的项目。
答
退房Need data from rails join table, has_many :through
试试这个。
user.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)? – 2012-02-20 02:40:20
是的,你可以随心所欲地调用它,但是除非你的愿望对象上也有一个'list_position'属性,那么应该这样做: – 2012-02-20 02:43:04
感谢您的帮助! – 2012-02-20 02:49:12