使用accepts_nested_attributes_for和decent_exposure设置关联ID

时间:2011-09-24 15:55:40

标签: ruby-on-rails nested-attributes simple-form

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

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

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

1 个答案:

答案 0 :(得分: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