我使用的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(還有一些額外的地方),但我還沒有能夠將這些概念翻譯成我的項目。
工作完美!所以這段代碼選擇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