2012-10-17 35 views
0

是否可以通过两个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 

回答

1

你的代码显示了试图做的事,你应该能够做到。它应该是这个样子:

@article = current_account.posts.build(params[:post]) 

因为你正在构建注销当前帐户的帖子列表中,你不必通过经常账户的ID。 (我不确定你的current_user是否与你的current_account相同,你可能想澄清一下)。

要将您的文章创建压缩为一行,您可以执行以下两件事之一。

  1. 将用户/作者和帖子之间的关系转换为双向关系。查看文档http://guides.rubyonrails.org/association_basics.html,其中订单属于客户,客户has_many订单。您可以自定义关系的名称,使帖子具有“作者”而不是用户,方法是将其称为“作者”,但后来使用class_name参数,我假设其值为:user。

  2. 在Post类中添加一个创建后挂钩,并将作者值设置为与当前用户相同。无法了解有关您的用户子系统的任何信息,我无法填写更多详细信息。

+0

我想你可能误会了我的问题。我添加了我的模型来澄清我的意思。我已经建立了一个作者协会。我的帐户由子域限定,每个帐户都有很多用户。我想确保在创建帖子时,它的作用域是当前帐号,通过子域获取,并且也与用户关联。 – Mohamad

+0

因此,current_account和current_user是不同的对象,并且你确实有一个帖子和作者two_way之间的关系。因此,您可以执行创建后挂钩建议,或者您可以将作为author的值传递给current_user,并与其他响应者显示的params合并,但使用不同的散列键值:@article = current_account.posts.build( params [:post] .merge({:author => current_user}))。这里最重要的是构建调用需要一个散列,其中散列的键是关联名称或正在构建的对象的字段名称。 – LisaD

1

params变量只是一个哈希,所以这些方针的东西应该工作给你一个衬垫:

@post = current_account.posts.build params[:post].merge({ :user_id => current_user.id }) 
+0

很好的建议,但我在我的可访问属性中包含'use_id',所以不幸的是会引发'MassAssignment :: Security'错误!尽管如此! +1 – Mohamad

相关问题