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.