Marius Turcu
2014-Aug-19 07:33 UTC
Rails 4 nested attributes multiple records insert instead updating
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" %> <%= f.select "lesson_icon", options_for_select([ "ico03", "ico04","ico05","ico06" ])%></br></br> <div> <%= 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: 'form-control'%></br> <%= sublesson_a.label :sublesson_video_link, "Video link" %><br> <%= sublesson_a.text_field :sublesson_video_link, class: "form-control" %></br> <%end%> </div> </div> <%= f.submit "Submit", class: "btn btn-primary" %> <% end %> </div> 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 -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/bfacf45d-9b96-4d3a-a736-dfc48738d23c%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.