2016-04-21 22 views
1

我有這些模型與關聯如下協會在三個模式

class User 
    has_many :comments 
    belongs_to :country 
end 

class Country 
    has_many :users 
    has_many :comments 
end 

class Comment 
    belong_to :user 
    belong_to :country 
end 

評論有user_idcountry_id作爲列名。 用戶有country_id作爲列名。

現在,如果我寫這個代碼是控制檯

User.first.comments.create :content=>"some content" 

這將創建一個評論,但評論的country_id列將是空的。我想country_id基於user_id 充滿我怎樣才能做到這

回答

2

可以設置country基於在userbefore_savebefore_create回調。這可以幫助你:

class User 
    has_many :comments 
    belongs_to :country 
end 

class Country 
    has_many :users 
    has_many :comments 
end 

class Comment 
    belong_to :user 
    belong_to :country 

    before_create :set_country 

    def set_country 
    self.country_id = user.country_id if user 
    end 
end 
1

,你必須明確地傳遞country_id

@user = User.first 
@user.comments.create(:content=>"some content", country_id: @user.country) 
+0

着它通過協會來完成,無需通過COUNTRY_ID明確 –

+1

@rohankharvi然後你使用回調'before_save'或'before_create'在你的模型@MaximPontyushenko已經可以做到這一點建議。 – dp7

1

嘗試以下:

u = User.first 
u.comments.create(content: "Some comment", country_id: u.country.id) 
2

評論總是會有與用戶相同的國家嗎?如果是這樣,你真的需要這種關係嗎?你可以從用戶的國家推斷評論的國家。

Class Comment 
    delegate :country, to: :user 
end 

comment.country將自動返回comment.user.country