0
我很新的軌道,所以這可能是一個愚蠢的問題,但我想知道如果我採取的方法來保存具有很多關係的對象是正確的。我爲保存具有關係的對象而採取的方法是正確的嗎?
例如:帶一個包含主題,帖子和用戶的基本論壇應用程序。該主題有一個用戶,一個論壇和許多帖子。如果用戶通過表單提交標題和消息,這是將數據保存在所有表格中最有效的方法,還是有一種更簡單的方法來實現它?
# 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
有沒有更好的習慣或者說它差不多呢?
這更有意義,但是當我做 @ user.build_topic(PARAMS [:專題]) 我得到 「未定義的方法'build_topic」爲#<用戶:0x007fcdd2718f48>」。 – Ken
我使用「@ user.topics.build(params [:topic])」而不是使用「build_topic」方法。我認爲這是因爲用戶對象has_many:主題。 – Ken