I have a Subject Model and a Lesson Model.
I implemented a nested model form.
After subject creation, I led it to a page where it supposedly shows the lessons associated. However, I fail to see the lessons.
I believe the data for lessons did not get saved properly as
When I did a for example lesson.find_by_subject_id(‘1’), I get ‘nil’ in return.
I am trying to figure out how polymorphism works on rails and would appreciate it if someone could either point out where I’ve gone wrong or give me some guidance on how those to pass the values for belong_to classes to be created.
Subject Model
attr_accessible :subjectCode, :lessons_attributes
has_many :lessons, :dependent => :destroy
accepts_nested_attributes_for :lessons, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
Lesson Model
attr_accessible :lessonName, :subject, :subject_id
belongs_to :subject
Subject Controller
def new
3.times {@subject.lessons.build}
end
def create
@subject = Subject.new(params[:subject])
if @subject.save
redirect_to @subject, :notice => "Successfully created subject."
else
render :action => 'new'
end
end
Form
<%= form_for @subject do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :subjectCode %><br />
<%= f.text_field :subjectCode %>
</p>
<%= f.fields_for :lessons do |builder| %>
<p>
<%= builder.label :lessonName %> <br/>
<%= builder.text_area :lessonName, :rows=>3 %>
</p>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
Routes
resources :subjects do resources :lessons end
Your
reject_iflambda will always reject the lessons attributes because lessons don’t have acontentattribute, so you’re essentially evaluatingnil.blank?which will returntruePerhaps you want to check if the lesson name is blank? Ala
:reject_if => lambda { |a| a[:lessonName].blank? }