Flame
Flame

Reputation: 7560

Foreign key in Ruby Rails

Hey I need help with the following set-up, I cant seem to find a solution:

User.rb

class User < ActiveRecord::Base
    has_one :education
end

Education.rb

class Education < ActiveRecord::Base
    belongs_to :user
end

-The Users table holds 'id'(id of the user) and 'education_id' and other columns which are of no importance now.

-The Educations table holds 'id' and 'name' which is the name of the education.

I'd like to get the Education name by using the *education_id* in the Users table to link to id in Educations.

I want to be able to use that in the view by using some syntax like

<%= user.education %>

I believe its a real simple solution but I cant seem to find it

Cheers

Upvotes: 0

Views: 92

Answers (2)

Aayush Khandelwal
Aayush Khandelwal

Reputation: 1071

by seeing the comment i think you need proper explanation first of all do

   class User < ActiveRecord::Base
       belongs_to :education
   end
   class Education < ActiveRecord::Base
       has_one :user
   end

the table which has the foreign key in this case education_id should have belongs_to( in this case ) user and the table of which the foreign key is created here education_id has has_one

Upvotes: 0

Salil
Salil

Reputation: 47462

Ref this

As per your Model declaration you should have user_id column in your educations table.

OR you have to change your model declaration to following

class User < ActiveRecord::Base
    belongs_to :education
end


class Education < ActiveRecord::Base
    has_one :user
end

Upvotes: 3

Related Questions