当我发布表单以创建带有子评论的新查询时(在应用程序中,查询可以有多个评论),评论没有建立。它在删除存在验证时起作用。所以它与构建和保存事物的顺序有关。如何保留验证并保持代码干净?
(以下是一个示例,因此可能无法完全运行)
模型/inquiry.rb
class Inquiry < ActiveRecord::Base
has_many :comments
accepts_nested_attributes_for :comments
模型/comment.rb
class Comment < ActiveRecord::Base
belongs_to :inquiry
belongs_to :user
validates_presence_of :user_id, :inquiry_id
控制器/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