I’m pretty new to rails, so this may be a dumb question, but I’m wondering if the approach I’m taking for saving objects with many relationships is correct.
For example: Take a basic forum app with topics, posts and users. The topic has one user, one forum, and many post. If the user submits a title and message via a form, is this the most effeicent way to save the data across all the tables, or is there a simpler way to do it?
# init new topic object with forum & user relationships
@topic = Topic.new(
:title => params[:topic][:title],
:forum_id => params[:topic][:forum_id],
:user_id => current_user.id
)
if @topic.save
# init new post object with topic & user relationships
@post = Post.new(
:content => params[:post][:content],
:topic_id => @topic.id,
:user_id => current_user.id
)
if @post.save
# update user's post count and last post info
@user = User.find(current_user.id)
@user.update_attributes(
:post_count => @user.post_count + 1,
:last_post_at => Time.now,
:last_post_id => @post.id
)
# update the forum stats and last post info
@forum = Forum.find(@topic.forum_id)
@forum.update_attributes (
:topic_count => @forum.topic_count + 1
:last_post_id => @forum.recent_post.nil? ? 0 : @forum.recent_post.id
)
# redirect user back to the topic
redirect_to topic_path(@topic.id)
end
Is there a better convention or is that pretty much it?
No, This is not a proepr way to write code in rails.
As per the rails your controller should be thin compare to model, so your buisness logic goes to the model and not to controller.
Check following review code
Use callback
after_createin your Post model i.e. post.rb to update the post counts of the user and AND callbackafter_createin your Topic model i.e. topic.rb to update the topic count of the forum.