是否可以通过两个has_many
关联建立一个对象?例如:通过Rails中的两个关联构建一个对象
# posts_controller.rb
def create
@post = current_account.posts.build(params[:post])
@post.author = current_user # I want to compact this line into the previous one
end
我做了一些研究,发现这一点:
@article = current_account.posts.build(params[:post], user_id: current_user.id)
但是,没有工作。在控制台中,每当我创建一个新对象时,我都会收到user_id: nil
。
我无法实现的另一种可能的解决方案:
@post = current_account.post_with_user(current_user).build(params[:post])
但post_with_user
每个执行我写失败。
我协会如下:
class Discussion < ActiveRecord::Base
belongs_to :account
belongs_to :author, class_name: 'User', foreign_key: 'user_id', inverse_of: :discussions
end
class User < ActiveRecord::Base
belongs_to :account
has_many :discussions, inverse_of: :author
end
class Account < ActiveRecord::Base
has_many :users, inverse_of: :account
has_many :discussions
end
我想你可能误会了我的问题。我添加了我的模型来澄清我的意思。我已经建立了一个作者协会。我的帐户由子域限定,每个帐户都有很多用户。我想确保在创建帖子时,它的作用域是当前帐号,通过子域获取,并且也与用户关联。 – Mohamad
因此,current_account和current_user是不同的对象,并且你确实有一个帖子和作者two_way之间的关系。因此,您可以执行创建后挂钩建议,或者您可以将作为author的值传递给current_user,并与其他响应者显示的params合并,但使用不同的散列键值:@article = current_account.posts.build( params [:post] .merge({:author => current_user}))。这里最重要的是构建调用需要一个散列,其中散列的键是关联名称或正在构建的对象的字段名称。 – LisaD