繁体   English   中英

保存前如何从post_params获取和使用对象的ID

[英]How can I get and use the id of an object from post_params before saving

我有3个模型。
用户-有很多评论
ISBN(一本书)-有很多评论
评论-属于用户,属于书籍

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

提交表单时,我想检查db中是否存在“ 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,这不是我想要的。

任何帮助将不胜感激。

我可能会通过在保存时在回调块中找到或创建与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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM