Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Rails 4 nested attributes multiple records insert instead updating


  • Please log in to reply
1 reply to this topic

#1 mariusturcu

mariusturcu

    Passenger

  • Members
  • 1 posts

Posted 19 August 2014 - 10:15 AM

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



#2 Anuj Dubey

Anuj Dubey

    Passenger

  • Members
  • 6 posts

Posted 24 September 2014 - 08:10 AM

update(id,attributes)

for multiple

Model.update([1,2],[{:language => "ruby",:framework => "rails"},{:ide => "aptana"}])

 

here you can use  update attributes

obj.update_attributes(attributes)

  • According to your code, you are using @lesson.update(lesson_params)





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users