2011-09-24 13 views
6

當我發佈表單以創建一個包含子註釋的新查詢時(在應用程序中,查詢可以有多個註釋),評論不會被構建。它在刪除存在驗證時有效。所以它與建立和保存事物的順序有關。如何保持驗證並保持代碼清潔?關聯標識沒有被設置爲使用accepting_nested_attributes_for和decent_exposure

(下面是一個例子,因此可能不完全可運行的)

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

請顯示構建這些表的遷移,或者如果沒有通過遷移構建,請顯示數據庫描述。 –

+0

以及我添加了schema.rb的提取 – linojon

回答

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