如何在保存之前从post_params获取和使用对象的id

时间:2016-04-26 02:54:42

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

我有3个型号 用户 - 有很多评论 ISBN(一本书) - 有很多评论 评论 - 属于User,属于Book

在我的评论表中,我有;
评论,
用户(将被隐藏)
ISBN

当我提交表单时,我想检查数据库中是否存在'isbn' 如果是,请添加评论,否则如果isbn尚不存在,则创建它并添加评论。

目前我可以使用以下方式找到存在:

def create
  if Isbn.exists?(isbn_number: comment_params[:isbn_id])
    create comment
  else 
    create isbn
    create comment
    save
  end
end

这将isbn数字保存为isbn_id,这不是我想要的。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我可能会通过在保存时在回调块中查找或创建与Isbn模型的关联来解决此问题。它可以这样做。

请注意,我在参数中使用:isbn_number而不是:isbn_id

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :isbn

  attr_accessor :isbn_number

  before_save do
    if @isbn_number.present?
      self.isbn = Isbn.where(isbn_number: @isbn_number).first_or_create!
    end
  end

end