# Rails 4 nested attributes multiple records when updating

**URL:** <https://www.ruby-forum.com/t/rails-4-nested-attributes-multiple-records-when-updating/231604>\
**Category:** Rails\
**Created:** [August 18, 2014, 7:41pm UTC](https://www.ruby-forum.com/t/rails-4-nested-attributes-multiple-records-when-updating/231604 "2014-08-18T19:41:24Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![addis\_a](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/c4cdca/32.png) [@addis\_a](https://www.ruby-forum.com/u/addis_a)\
**Post date:** [August 18, 2014, 7:41pm UTC](https://www.ruby-forum.com/t/rails-4-nested-attributes-multiple-records-when-updating/231604/1 "2014-08-18T19:41:24Z")

</div>

I’m stuck and i don’t know why it is not working right. I have a model  
lesson wich has many sublessons. When i update the lesson rails update  
properly the lesson attributes but is creating another sublessons  
records instead of just updating it.

Here is my code

View Form:

\<%= form\_for @lesson do |f| %\> \<%= f.label :lesson\_name, "Lesson title" %\> \<%= f.text\_field :lesson\_name, class: "form-control" %\> \<%= f.label :lesson\_icon, "Choise icon" %\> \<%= f.select "lesson\_icon", options\_for\_select(["ico03", "ico04","ico05","ico06"])%\> 
 \<%= f.fields\_for :sublessons do |sublesson\_a| %\>

```
       <%= sublesson_a.label :sublesson_name, "Subtitle 1" %></br>
       <%= sublesson_a.text_field :sublesson_name, class:

```

“form-control” %\>  
\<%= sublesson\_a.label :sublesson\_content, “Content” %\>  
\<%=sublesson\_a.text\_area ‘sublesson\_content’, rows: 3, class:  
‘form-control’%\>  
\<%= sublesson\_a.label :sublesson\_video\_link, “Video link”  
%\>  
  
\<%= sublesson\_a.text\_field :sublesson\_video\_link, class:  
“form-control” %\>  
\<%end%\>

  

  
\<%= f.submit “Submit”, class: “btn btn-primary” %\>

\<% end %\>

lesson model  
class Lesson \< ActiveRecord::Base  
has\_many :sublessons, :dependent =\> :destroy  
accepts\_nested\_attributes\_for :sublessons, :reject\_if =\> :all\_blank  
end  
sublesson model

class Sublesson \< ActiveRecord::Base  
belongs\_to :lesson, :foreign\_key =\> “lesson\_id”  
validates :sublesson\_name, presence: true  
validates :sublesson\_content ,presence: true  
end

lesson controller

def update  
@lesson = Lesson.find(params[:id])  
@sublessons=@lesson.sublessons.all  
if @lesson.update(lesson\_params)  
flash[:notice] = “Lesson updated”  
redirect\_to lessons\_show\_url  
else  
flash[:notice] = “Error”  
redirect\_to lessons\_show\_url  
end  
end

def edit  
@lesson = Lesson.find(params[:id])  
@sublessons=@lesson.sublessons.all  
end

def lesson\_params  
params.require(:lesson).permit(:lesson\_name, :lesson\_icon,  
sublessons\_attributes:[:sublesson\_id, :sublesson\_name,  
:sublesson\_content, :sublesson\_video\_link])  
end
