ActiveRecord::UnknownAttributeError in rails application

342 Views Asked by At

I have two model, one as follow

class Course < ActiveRecord::Base
  has_many :assignments, class_name: 'Assignment', foreign_key: :assignment_id, dependent: :destroy
  has_many :groups, class_name: 'Group', foreign_key: :group_id, dependent: :destroy
end

And another model

class Assignment < ActiveRecord::Base
  belongs_to :course, class_name: 'Course', foreign_key: :course_id
  has_many :questions, class_name: 'Question', foreign_key: :question_id, dependent: :destroy
end

These two has relationship one to many i.e a course can have many assignments but an assignment belongs to a course.

In my assignment/index.html.erb view I have following form

<%= form_tag({controller: "assignments", action: "new"}, method: "get", class: "nifty_form") do %>
    <%= select_tag "course", options_from_collection_for_select(Course.all, :id, :name) %> <br /><br />
    <%= submit_tag("New Assignment") %>
<% end %>

New method of my assignments_controller.rb

def new
    @course = Course.find(params[:course])
    @assignment = @course.assignments.build
  end

When I submit the above form I get error at this line @assignment = @course.assignments.build

ActiveRecord::UnknownAttributeError in AssignmentsController#new
unknown attribute: assignment_id

assignment_id and course_id are not a column in the any of the table. How to fix this error?

Also I am new to rails. Since I have one to many relation, I am trying to create database as @assignment = @course.assignments.build is this the right way? I mean do I have to write @course.assignments.build or just @assignment = Assignment.new is okay? Also the way I wrote the relationships with foreign key is it correct?

2

There are 2 best solutions below

0
On

The belongs_to table MUST have the foreign keys defined as columns in the table. How do you think the records will be linked, otherwise?

So your assignments table should have an integer column course_id. Create it with a migration.

Then all you need is...

class Course < ActiveRecord::Base
  has_many :assignments, dependent: :destroy

and...

class Assignment < ActiveRecord::Base
  belongs_to :course

Then this will work...

@assignment = @course.assignments.build
3
On

You don't have to specify class_name and foreign_key, when you follow convention, as it is in your case.

@assignment = @course.assignments.build is a right way, because you want to specify relationship between course and assignment. You can do this: @assignment = Assignment.new(course: @course), but use first method.

Edit: I assume that you have assignment_id attribute in Course:)