我用来保存关系对象的方法是否正确?

时间:2012-09-12 05:56:49

标签: ruby-on-rails ruby activerecord

我对rails非常陌生,所以这可能是一个愚蠢的问题,但我想知道我用来保存具有多种关系的对象的方法是否正确。

例如:使用包含主题,帖子和用户的基本论坛应用。该主题有一个用户,一个论坛和许多帖子。如果用户通过表单提交标题和消息,这是在所有表中保存数据的最有效方式,还是有更简单的方法呢?

# 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 个答案:

答案 0 :(得分:1)

不,这不是一种在rails中编写代码的方法。 根据轨道,与模型相比,您的控制器应该很薄,因此您的商务逻辑会转到模型而不是控制器。

检查以下审核代码

@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

在Post模型中使用回调after_create,即post.rb更新用户的帖子计数和主题模型中的AND回调after_create,即topic.rb,以更新论坛的主题数量