我将这些模型与关联关联如下
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_id
和country_id
作为列名。
用户名为country_id
。
现在,如果我写这个代码是控制台
User.first.comments.create :content=>"some content"
这会创建一条评论,但评论的country_id
列将为空。我想根据country_id
填写user_id
我该怎么做
答案 0 :(得分:2)
您可以使用country
或user
回调基于before_save
设置before_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 :(得分:2)
评论是否始终与用户具有相同的国家/地区?如果是这样,你真的需要这种关系吗?您只需从用户所在国家/地区推断评论的国家/地区即可。
Class Comment
delegate :country, to: :user
end
然后 comment.country
会自动返回comment.user.country
答案 2 :(得分:1)
你必须明确地传递country_id
:
@user = User.first
@user.comments.create(:content=>"some content", country_id: @user.country)
答案 3 :(得分:1)
尝试以下方法:
u = User.first
u.comments.create(content: "Some comment", country_id: u.country.id)