yerassyl
yerassyl

Reputation: 3058

has_many and belongs_to assosiations in Rails 4

everyone I have a question related relationships in Rails. I have a Student model

class Student < ActiveRecord::Base
    ....
    has_many :histories, dependent: :destroy
end
                                  
                                 
And my History model

class History < ActiveRecord::Base
	belongs_to :student
	
end

I try to this code to get all histories that belong to a student

def history
@histories = @student.histories.paginate(:per_page =>25, :page => params[:page])
end
Method history belongs to Students controller, and is called via history_path(student). But i got an error :no such column: histories.student_id. I thought that when i make relationships in Rails via belongs_to and has_many necessary id's are created automatically?

Upvotes: 1

Views: 46

Answers (2)

ClassyPimp
ClassyPimp

Reputation: 725

You've to try running:

rails g migration create_histories student:references; rake db:migrate

This will create histories table with student_id. Or add user:references to your existing histories table

Deep answered first while I was typing, avoid my answer.

Upvotes: 0

Deepesh
Deepesh

Reputation: 6418

No they are not automatically created. Just create a migration like this:

rails g migration add_student_id_to_histories student_id:integer

and then run:

bundle exec rake db:migrate

This needs to be done for all the relations. Rails doesn't automatically creates this. You need to do this manually.

Upvotes: 0

Related Questions