简体   繁体   English

Ruby Rails中的外键

[英]Foreign key in Ruby Rails

Hey I need help with the following set-up, I cant seem to find a solution: 嘿,我需要以下设置的帮助,我似乎找不到解决方法:

User.rb User.rb

class User < ActiveRecord::Base
    has_one :education
end

Education.rb 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. -“用户”表包含“ id”(用户的id)和“ education_id”以及其他现在不重要的列。

-The Educations table holds 'id' and 'name' which is the name of the education. -“教育”表包含“ id”和“名称”,即教育名称。

I'd like to get the Education name by using the *education_id* in the Users table to link to id in Educations . 我想通过使用Users表中的* education_id *链接到Educations中的id来获取Education的名称

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. 根据您的模型声明,您的教育表中应该有user_id列。

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 在这种情况下具有外键的表Education_id应该具有belongs_to(在这种情况下)用户,并且在此处创建外键的表education_id具有has_one

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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