1

所以我有一個應用程序,用戶可以在其中創建汽車。他們也可以喜歡汽車,我想在兩者之間建立聯繫。他們創造的汽車屬於他們,他們喜歡的汽車通過喜歡他們的背景屬於他們。要做到這一點,我已經建立了我的協會如下:相同模型的多態協會Ruby on Rails 4

用戶協會:

class User < ActiveRecord::Base 
    has_many :cars 
    has_many :cars, -> {distinct}, through: :likes 
end 

汽車協會:

class Car < ActiveRecord::Base 
    belongs_to :users 
    has_many :likes 
    has_many :users, -> { distinct }, through: :likes 
end 

像協會:

class Like < ActiveRecord::Base 
belongs_to :user 
belongs_to :car 
end 

的問題是,之前我有我的用戶has_many汽車通過類似的關係聲明。我曾經可以打電話給@ user.cars,它會顯示用戶的汽車。現在它返回用戶喜歡的汽車的集合。我需要每個集合的方法。

當我嘗試:User.likes.cars

我得到一個

No Method error

和控制檯日誌通過查找喜歡的記錄,仍然沒有歸還汽車,即使我喜歡記錄有car_id場。

我看了一堆問題,但無法理解它們。我也試圖在模型中定義方法,而且似乎沒有任何工作可行。任何幫助表示讚賞。

我將如何更改我的關聯,以便可以同時查詢User.cars(用戶創建的汽車)和User.likes.cars(用於用戶喜歡的汽車)?

回答

2

因此,奧列格的下面的答案並不完全正確,但帶領我走向正確的方向。謝謝!我開始按照上面的例子,做:

class User < ActiveRecord::Base 
     has_many :cars 
     has_many :car_likes, -> {distinct}, class_name: 'Car', through: :likes 
    end 

    class Car < ActiveRecord::Base 
     belongs_to :users 
     has_many :likes 
     has_many :user_likes, -> { distinct }, class_name: 'User', through: :likes 
     end 

這在控制檯返回以下錯誤:

ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) "car_likes" or :car_like in model Like. Try 'has_many :car_likes, :through => :likes, :source => '. Is it one of user or car?

所以我把它改爲:

class User < ActiveRecord::Base 
    has_many :cars 
    has_many :car_likes, -> {distinct}, through: :likes, source: :cars 
end 
Car Association: 

class Car < ActiveRecord::Base 
    belongs_to :users 
    has_many :likes 
    has_many :user_likes, -> { distinct }, through: :likes, source: :users 
end 

它NOW的兩個作品楷模!謝謝,希望這對於有同樣問題的其他人有幫助。

0

has_many :cars, -> {distinct}, through: :likes優先於has_many :cars,因爲它重新定義了User.cars。請嘗試以下操作:

class User < ActiveRecord::Base 
    has_many :cars 
    has_many :car_likes, -> {distinct}, class_name: 'Car', through: :likes 
end 
Car Association: 

class Car < ActiveRecord::Base 
    belongs_to :users 
    has_many :likes 
    has_many :user_likes, -> { distinct }, class_name: 'User', through: :likes 
end 

#To get them, instead of user.likes.cars 
@user.car_likes 
@car.user_likes 

如果問題仍然存在,請讓我知道。可能有另一個錯誤。

0

我沒有看到你在哪裏定義任何模型爲多態。

在過去,我已經做了這樣的事情..其實我做了這個標籤/標籤,並「使」用戶應用於另一個實例的標籤。這是一個特別的修改,我可能錯過了一些東西,但這對於多態關聯是一個非常常見的用例。

class Like < ActiveRecord::Base 
    belongs_to :likeable, polymorphic: true 
    ... 
end 

class Liking < ActiveRecord::Base 
    belongs_to :like 
    belongs_to :likeable, :polymorphic => true 
end 

class User < ActiveRecord::Base 
    has_many :likings, :as => :likeable 
    has_many :likes, -> { order(created_at: :desc) }, :through => :taggings 
end