0

我对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

有更好的约定还是差不多?

4

1 回答 1

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

Use callback after_create in your Post model i.e. post.rb to update the post counts of the user and AND callback after_create in your Topic model i.e. topic.rb to update the topic count of the forum.

于 2012-09-12T06:15:13.670 回答