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?
The
belongs_totable MUST have the foreign keys defined as columns in the table. How do you think the records will be linked, otherwise?So your
assignmentstable should have an integer columncourse_id. Create it with a migration.Then all you need is...
and...
Then this will work...