简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM