2011-09-24 13 views
6

子コメント付きの新しい照会を作成するフォームを投稿すると(アプリ内で複数のコメントがある可能性があります)、コメントは作成されません。存在確認を削除するときに機能します。それは物事が築かれ救われる順序と関係しています。検証を保持してコードをきれいに保つ方法accepts_nested_attributes_forとdecent_exposureを使用してアソシエーションIDが設定されていません

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 inquiry.rb/

モデル

は(それが正確runableではないかもしれないので、以下は例です)。 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! 

または代替の方法は

基本的にあなたのコメントフォーム

= c.hidden_field :inquiry_id, inquiry.id 
に以下の行を追加し
= 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 

だろう

関連する問題