1

I have a model Subject and a nested Model Lessons

I am encountering the problem of unknown attribute: subject_id

I have tried the different solutions suggested at Rails 3 Nested Models unknown attribute Error but I am still receiving the error.

I am pretty new to Rails and I can't seem to figure out what went wrong. I would appreciate it if someone could help me out.

Here are my relevant files.

Subject Model

  attr_accessible :subjectCode, :subject_id

  has_many :lessons, :dependent => :destroy
  accepts_nested_attributes_for :lessons, :reject_if => lambda { |a| a[:content].blank?     }, :allow_destroy => true

end

Lesson Model

  attr_accessible :lessonName
  belongs_to :subject

Subject Controller

def show
  @subject = Subject.find(params[:id])
end

def new
  @subject = Subject.new
  @lesson = @subject.lessons.build
end

def create
  @subject = Subject.new(params[:subjectCode])
  if @subject.save
    redirect_to @subject, :notice => "Successfully created subject."
  else
    render :action => 'new'
  end
end

Subject Form

<%= form_for @subject do |f| %>
<%= f.error_messages %>
<p>
  <%= f.label :subjectCode %><br />
  <%= f.text_field :subjectCode %>
</p>
<%= f.fields_for :lessons, @lesson do |builder| %>
<p>    
<%= builder.label :lessonName %> <br/>
<%= builder.text_area :lessonName, :rows=>3 %>
</p>
<% end %>
<p><%= f.submit "Submit" %></p>

routes.rb

resources :subjects do resources :lessons end
Community
  • 1
  • 1
Butter Beer
  • 1,100
  • 3
  • 16
  • 32

1 Answers1

0

The subject_id should be put in Lesson model, because it belongs to Subject, you should put it in accessible too, and also puts lessons_attributes in attr_accessible in Subject model. I think the code to build Subject in your create action should be:

@subject = Subject.new(params[:subject]), not

@subject = Subject.new(params[:subjectCode])

Try this and see something happens.

Thanh
  • 8,219
  • 5
  • 33
  • 56
  • I have found the solution. I missed out the subject_id column in the lessons table. I did a migration and it worked. Thanks for your help anyway. – Butter Beer Nov 01 '12 at 18:37