Association ID is not set using accepts_nested_attributes_for and positive_exposure

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 
+6
source share
1 answer

Basically, before saving, you also check for the presence of query_id, the association of the return from the comment to the query, which cannot be set until the comment is saved. An alternative way to achieve this is still not valid for your checks:

 comment = Comment.new({:user => current_user, :body => params[:body] comment.inquiry = inquiry comment.save! inquiry.comments << comment inquiry.save! 

Or an alternative way would be

 = 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 

Basically adding the following line to the comment form

  = c.hidden_field :inquiry_id, inquiry.id 
+1
source

Source: https://habr.com/ru/post/897972/


All Articles