6

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

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

模型/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
4

1 回答 1

1

基本上,在保存之前,您还要测试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
于 2012-06-20T02:26:42.603 回答