This is a consistency problem that I’m running into often.
Let’s consider a typical Forum:
- User can create Posts
- Posts belong to a Topic
- Posts also belong to the User that created them
What’s the best practice for choosing between these two options:
# Initialize @post on the User
def create
@post = current_user.posts.build(params[:post])
@post.topic_id = @topic.id
if @post.save
...
end
end
Or
# Initialize @post on the Topic
def create
@post = @topic.posts.build(params[:post])
@post.user_id = current_user.id
if @post.save
...
end
end
Or is there a better way, considering that, in the above examples, either @post’s user_id or topic_id would have to be added to attr_accesssible (feels hacky)?
You never need to monkey with IDs or attr_accessible. If a User
has_manyPosts and a Topichas_manyPosts than you can doThere really isn’t a big difference in building from the user or from the topic, but going from the user seems more natural to me.