2012-09-12 25 views
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 

有沒有更好的習慣或者說它差不多呢?

回答

1

不,這不是在rails中編寫代碼的proepr方法。 根據導軌,您的控制器應該與模型相比較薄,因此您的buisness邏輯將轉至模型而不是控制器。

檢查以下審查代碼

@user = User.find(current_user.id) 
@topic = @user.build_topic(params[:topic]) 
@post = @topic.posts.build(:content => params[:post][:content], :user_id => @user.id) 
if @topic.save #Don't need to save posts explicitly if any error (i.e validation fails) is occur neither post nor topic 'll get save 
    # redirect user back to the topic 
    redirect_to topic_path(@topic.id) 
end 

使用回叫after_create在Post模型即post.rb更新和您的主題模型,即topic.rb更新主題的用戶的職位數和回調after_create計算的論壇。

+0

這更有意義,但是當我做 @ user.build_topic(PARAMS [:專題]) 我得到 「未定義的方法'build_topic」爲#<用戶:0x007fcdd2718f48>」。 – Ken

+1

我使用「@ user.topics.build(params [:topic])」而不是使用「build_topic」方法。我認爲這是因爲用戶對象has_many:主題。 – Ken

相關問題