轨道上的红宝石关系引用保存



我只是想知道保存此类数据的最佳实践是什么

这是模型的关系

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 解析它

你可以写这样的东西:

@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))

更新:

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

# 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)

最新更新