Rails 3 How to assign the value to nested attributes before calling save in update action

I am using Rails 3.0.9 and Ruby 1.9.2

Models associations are

has_many :sections
accepts_nested_attributes_for :sections, :allow_destroy => :true,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }

belongs_to :document
has_many :paragraphs, :dependent => :destroy
has_many :contents :through => :paragraphs
validates :user_id, :presence => { :message => “Must be filled” }

attr_accessible :user_id, :section_id, :content_id
belongs_to :section
belongs_to :content
validates :user_id, :section, :content, :presence => { :message =>
“Must be filled” }

paragraphs table just like a intermediate table for sections and
contents and I want to save records in documents, sections and
paragraphs table using single form submission.


<%= form_for @document, :validate => true do |f| %>
 <%= f.error_messages %>
 <div><%= f.text_field :name %></div>

 <% f.fields_for :sections do |builder| %>
   <div><%= builder.text_field :name %></div>
    <%= builder.select :content_ids,
     Content.all.collect {|p| [ p.name, p.id ] },
     {:prompt => "Please Select"}, {:class => "nhs_select",
        :multiple => true}  %>
    <% end %>
    <%= f.submit :submit%>

<% end %>

Example parameters when submiting the form
“sections_attributes”=>{“0”=>{“name”=>“sdf”, “description”=>“sdf”,
“_destroy”=>“0”, “content_ids” => [“1”, “2”]}}, “commit”=>“Create

In additionally, I should need to update current_user’s id to user_id
column of paragraphs table.

def create
@document = Document.new
@document.attributes = params[:document]
@document.sections.each {|section|
section.user_id = current_user.id
section.paragraphs.each {|paragraph| paragraph.user_id =
if @document.save!
# success
render :action => ‘new’

Problem 1:

At first, I submit the form, rails render new form without error message
even I have implemented code to display error messages.

then again clicked submit button, action goes to update method. But it
should go to new action.

I inspected in console, the inserted records were rollbacked but still
the ID is retain in object.


Problem 2:

Documentation said that the changes are not saved to the database when
assigning the attributes as like user.attributes = {:name => “Rob”}.

but my case validation is triggered when assigning the attributes so I
can’t assign the value to user_id column in paragraph object before
calling save method

@document.attributes = {“sections_attributes”=>{“0”=>{“name”=>“sdf”,
“content_ids” => [“1”, “2”]}}
section = Section.first
section.attributes = {“content_ids” => [“1”, “2”]}

How to assign the value to user_id in paragraph object before calling
save method

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs