Forum: Ruby on Rails Rails 4 nested attributes multiple records when updating

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
A551dd246cb624b7fd6a78d5ccee835d?d=identicon&s=25 Turcu Marius (mariusturcu)
on 2014-08-18 19:41
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:
<div style="padding:13px">
<%= form_for @lesson do |f| %>
          <%= f.label :lesson_name, "Lesson title" %></br>
          <%= f.text_field :lesson_name,  class: "form-control" %></br>
          <%= f.label :lesson_icon, "Choise icon" %>
          <%= "lesson_icon", options_for_select([ "ico03",
"ico04","ico05","ico06" ])%></br></br>
           <%= f.fields_for :sublessons do |sublesson_a| %>

           <%= sublesson_a.label :sublesson_name, "Subtitle 1" %></br>
           <%= sublesson_a.text_field :sublesson_name, class:
"form-control" %></br>
           <%= sublesson_a.label :sublesson_content, "Content" %></br>
           <%=sublesson_a.text_area 'sublesson_content', rows: 3, class:
           <%= sublesson_a.label :sublesson_video_link, "Video link"
           <%= sublesson_a.text_field :sublesson_video_link, class:
"form-control" %></br>
<%= 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
sublesson model

class Sublesson < ActiveRecord::Base
  belongs_to :lesson, :foreign_key => "lesson_id"
  validates :sublesson_name, presence: true
  validates :sublesson_content ,presence: true

lesson controller

def update
   @lesson = Lesson.find(params[:id])
    if @lesson.update(lesson_params)
      flash[:notice] = "Lesson updated"
      redirect_to lessons_show_url
      flash[:notice] = "Error"
      redirect_to lessons_show_url

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

def lesson_params
params.require(:lesson).permit(:lesson_name, :lesson_icon,
sublessons_attributes:[:sublesson_id, :sublesson_name,
:sublesson_content, :sublesson_video_link])
This topic is locked and can not be replied to.