When I submit a form to create a new request with a child comment (in the application, requests may have several comments), a comment is not created. It works when presence checks are removed. Thus, this is related to the order in which things are created and stored. How to keep checks and keep code clean?
(The following is an example, so it may not be entirely accurate)
Models / inquiry.rb
class Inquiry < ActiveRecord::Base has_many :comments accepts_nested_attributes_for :comments
models / comment.rb
class Comment < ActiveRecord::Base belongs_to :inquiry belongs_to :user validates_presence_of :user_id, :inquiry_id
Controllers / 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
views / requests / 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
database schema
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
source share