帖子属于主题和用户。如何使用:topic_id和:user_id创建帖子而不暴露attr_accessible?

时间:2011-05-10 21:43:51

标签: ruby-on-rails-3 activerecord

我正在制作一个传统的论坛来学习/练习Rails。您熟悉的是,用户可以创建主题和帖子。主题和帖子属于创建它们的用户,帖子属于他们发布的主题。注意:帖子是主题的嵌套资源。

User Model
  has_many :topics
  has_many :posts

Topic Model
  has_many :posts
  belongs_to :user

Post Model
  belongs_to :user
  belongs_to :topic

因此,当用户创建新帖子时,帖子需要user_idtopic_id

我知道范围界定与:

@user.posts.create(:title => "My Topic.")
@topic.posts.create(:content => "My Post.")

但这些示例仅分别设置user_idtopic_id,而不是两者。

我的问题

我该怎么做:

@topic.posts.create(:content => "This is Dan's post", :user_id => @dan.id)

无需通过user_id

在Post模型中公开attr_accessible :user_id

换句话说,我不想明确定义:user_id

我尝试过这样的事情:

dans_post = @user.posts.new(:content => "the content of my post")
@topic.posts.create(dans_post)

无济于事。

1 个答案:

答案 0 :(得分:2)

使用build构建关联,而不是new,因为它将正确定义外键。要解决您的问题,请使用merge将用户合并到帖子的参数:

@topic.posts.build(params[:post].merge(:user => current_user))