2011-06-22 38 views
1

我有一位作者,他寫的是分組放置的產品。 我想要做的是列出作者參與的組。獲得對象的名稱,後面跟兩次關係(2x has_many)

所以,我首先要遵循從作者到的產品,這與作品的鏈接:

@author = Author.find(params[:id]) 
@products = @author.products 

這給很多產品:-)然後,我必須要找到(全部)鏈接組所有產品(因爲一組可以包含很多產品,我必須在產品表GROUP_ID列已經是的has_many鏈接)

但是當我嘗試寫一些東西作爲

@groups = @author.products.groups 

我得到錯誤:未定義的方法`組'爲#類:0x000000032a2198

爲什麼?

這裏是模型,只有「通過」條款似乎不起作用?

class Author < ActiveRecord::Base 
    has_and_belongs_to_many :products 
    has_many :groups, :through => :products 
end 
class Product < ActiveRecord::Base 
    belongs_to :group 
    has_and_belongs_to_many :authors 
end 
class Group < ActiveRecord::Base 
    has_many :products, :dependent => :destroy 
    has_many :authors, :through => :products 
end 

謝謝!

編輯:我發現了一個醜陋的方式來做我想做的事。 但是沒有更好的RoR方式嗎?

def show 
@author = Author.find(params[:id]) 
    @products = @author.products 
    @groups = [] 
    @products.each do |product| 
     group = Group.find(product.group_id) 
     unless @groups.include?(group) 
      @groups << group 
     end 
    end 
end 

回答

1

據我知道有沒有辦法做到這一點在Rails的方式。首先,這裏是如何讓你有更多的「Railsy」:

def show 
    @author = Author.find(params[:id]) 
    @products = @author.products 
    @groups = [] 
    @products.each do |product| 
    unless @groups.include?(product.group) 
     @groups << group 
    end 
    end 
end 

但較短的辦法是:什麼它做

@products.map(&:group).uniq 

快速的解釋。首先,它使用符號來處理Rails 1.1中引入的簡寫(http://blog.hasmanythrough.com/2006/3/7/symbol-to-proc-shorthand)。這構建了一組組。然後b/c,在你的問題中,你正在檢查的唯一性(使用包括?)我打電話.uniq淘汰任何重複。

+0

我喜歡你的最後一句話......但我只知道這個詞「uniq的」,這表示你正在構建一個大桌子,在...之後會減少,我要檢查這個文檔。 Thx幫助! –

+0

對不起,但你的簡化不適合我。 NameError在AuthorsController#顯示 未定義的局部變量或方法'羣」爲#AuthorsController:0x0000000282c538 看來,‘羣’是從‘產品’未知的,但我有一個的has_many/belongs_to的鏈接...? –

+0

打開rails控制檯(Rails 3:rails c; Rails 2:script/console)並鍵入「Product.first.group」。假設Product.first不爲零,如果返回錯誤,則會出現更深層次的問題。雖然,你原來的問題看起來是正確的(關於產品/組關係)。 – pcg79

0

我還發現了另一種方式來做到這一點:

@user = User.find(params[:id]) 
@groupcollect = [] 
@user.products.each { |e| @groupcollect << e.group_id} # collect group_id for all products 
@mygroups = Group.find(@groupcollect.uniq)  # gets the groups for all group_id, unique 

:-)