1

I'm making a conventional forum to learn/practice Rails. As you're familiar with, Users can create Topics and Posts. Topics and Posts belong to the User that created them, and Posts belong to the Topic they were posted in. Note: Post is a nested resource of Topic.

User Model
  has_many :topics
  has_many :posts

Topic Model
  has_many :posts
  belongs_to :user

Post Model
  belongs_to :user
  belongs_to :topic

So, when a User creates a new Post, the Post needs a user_id and a topic_id.

I know about scoping associations with:

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

But those examples only set user_id and topic_id respectively, not both.

My Question

How can I do something like this:

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

Without having to expose user_id in the Post model via attr_accessible :user_id?

In other words, I don't want to have to explicitly define :user_id.

I tried things like:

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

to no avail.

danneu
  • 9,244
  • 3
  • 35
  • 63

1 Answers1

2

Use build for building associations, instead of new, as it will define the foreign key correctly. To solve your problem, use merge to merge in the user to the parameters for the post:

@topic.posts.build(params[:post].merge(:user => current_user))
Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • `.new` builds foreign keys in Rails 3. I did find a pretty good [explanation](http://stackoverflow.com/questions/4954313/build-vs-new-in-rails-3) of the difference between `new` and `build` on associations, though. `.merge(:user => current_user)` expects `:user_id` to be exposed by `attr_accessible` while `@post.creator = current_user` does not. I guess I can live with having to specify @post.creator on a second line. – danneu May 11 '11 at 06:30
  • @Ryan Bigg How to create post for a user from api? i gave as below current_user.posts.build(:params[:content]) but its showing user_id cant be blank in rails3 – useranon Feb 20 '12 at 06:17
  • @Jasmine: Don't `validate_presence_of :user_id`. That's what is causing this problem. – Ryan Bigg Feb 20 '12 at 13:21