当我发布一个表单来创建一个带有子评论的新查询时(在应用程序中,查询可以有多个评论),评论不会被构建。当删除存在验证时,它会起作用。因此,它与构建和保存事物的顺序有关。如何保存验证并保持代码的整洁?
(以下是一个示例,因此它可能不是完全可运行的)
models/quiiry.rb
class Inquiry < ActiveRecord::Base
  has_many :comments
  accepts_nested_attributes_for :commentsmodels/comment.rb
class Comment < ActiveRecord::Base
  belongs_to :inquiry
  belongs_to :user
  validates_presence_of :user_id, :inquiry_id控制器/inquiry_controllers.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发布于 2012-06-20 10:26:43
基本上,在保存之前,您还在测试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.idhttps://stackoverflow.com/questions/7540087
复制相似问题