Ruby on rails关系参考保存

时间:2014-12-02 07:54:07

标签: ruby-on-rails ruby ruby-on-rails-4

我只是想知道保存这类数据的最佳做法是什么

这是模型的关系

class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
  has_many :comments, dependent: :destroy
end

class Comment < ActiveRecord::Base
    belongs_to :post
    belongs_to :user
end

class Post < ActiveRecord::Base
    belongs_to :user
    has_many   :reviews
end

目前我正在将它们保存在这种代码中

def create
    @post = Post.find(params[:post_id])
    @comment = current_user.reviews.build(comment_param)
    @comment.post_id = params[:post_id]
    if @comment.save
        flash[:success] = 'Successfully created a comment'
        @post
    else
        flash[:error] = 'Error'
        @post
    end
end

这是表格开头标记。

form_for([@post,@post.comment.build]) do |f|
    %p
       = f.label :title, class: 'control-label'
       = f.text_field :title, class: 'form-control'
    %p
       = f.label :message, class: 'control-label'
       = f.text_area :message, class: 'form-control'

我如何快捷方式,以便我不会手动分配post_id并让rails解析它

1 个答案:

答案 0 :(得分:0)

你可以这样写:

@comment = current_user.comments.build(comment_param.merge(:post_id => params[:post_id]))

@post = Post.find(params[:post_id])
@comment = @post.comments.build(comment_param.merge(:user => current_user))

<强>更新

或者您可以向scope模型添加Comment

# in comment.rb
scope :by_user, ->(user) { where(:user_id => user.id) }

# and then in the controller
@post = Post.find(params[:post_id])
@comment = @post.comments.by_user(current_user).build(comment_param)