gpt4 book ai didi

ruby-on-rails - 使用accepts_nested_attributes_for 和denefit_exposure 未设置关联ID

转载 作者:行者123 更新时间:2023-12-04 03:46:12 25 4
gpt4 key购买 nike

当我发布一个表单来创建一个带有子评论的新查询时(在应用程序中,查询可以有多个评论),评论没有被构建。它在删除存在验证时起作用。所以它与构建和保存事物的顺序有关。如何保留验证并保持代码干净?

(以下是一个示例,因此它可能无法完全运行)

模型/查询.rb

class Inquiry < ActiveRecord::Base
has_many :comments
accepts_nested_attributes_for :comments

模型/评论.rb
class Comment < ActiveRecord::Base
belongs_to :inquiry
belongs_to :user
validates_presence_of :user_id, :inquiry_id

Controller /inquiry_controller.rb
expose(:inquiries)
expose(:inquiry)

def new
inquiry.comments.build :user => current_user
end

def create
# inquiry.save => false
# inquiry.valid? => false
# inquiry.errors => {:"comments.inquiry_id"=>["can't be blank"]}
end

意见/查询/new.html.haml
= simple_form_for inquiry do |f|
= f.simple_fields_for :comments do |c|
= c.hidden_field :user_id
= c.input :body, :label => 'Comment'
= f.button :submit

数据库模式
create_table "inquiries", :force => true do |t|
t.string "state"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "comments", :force => true do |t|
t.integer "inquiry_id"
t.integer "user_id"
t.text "body"
t.datetime "created_at"
t.datetime "updated_at"
end

最佳答案

基本上,在保存之前,您还要测试inquiry_id 的存在,即从评论到查询的返回关联,在保存评论之前无法设置。实现此目的并仍然保持验证完整的另一种方法如下:

comment = Comment.new({:user => current_user, :body => params[:body]
comment.inquiry = inquiry
comment.save!
inquiry.comments << comment
inquiry.save!

或者另一种方式是
= simple_form_for inquiry do |f|
= f.simple_fields_for :comments do |c|
= c.hidden_field :user_id
= c.hidden_field :inquiry_id, inquiry.id
= c.input :body, :label => 'Comment'
= f.button :submit

基本上在您的评论表单中添加以下行
    = c.hidden_field :inquiry_id, inquiry.id

关于ruby-on-rails - 使用accepts_nested_attributes_for 和denefit_exposure 未设置关联ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7540087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com