本文介绍了创建并在执行HAS_ONE关系轨关系型数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在工作中看到的配置文件表。那种我有一个问题设置它,这是正确的?我感到困惑的的has_many和HAS_ONE关系。因为这是一个表,有一个排的每个访问的关系,我决定去与HAS_ONE。Working on a table of viewed profiles. I kind of have an issue setting it up, is this correct? I am confused about the has_many and has_one relationship. Because this is one table that has a row for each visited relationship, I decided to go with has_one.这是否看起来是正确的,也有没有办法强制执行的ActiveRecord的关系?Does this look correct, also is there a way to enforce the relation in ActiveRecord?class ViewedProfile < ActiveRecord::Base validates :viewed_profile_id, presence: true validates :profile_id, presence: true has_one :profile_id has_one :viewed_profile_idend迁移class CreateViewedProfile < ActiveRecord::Migration def change create_table :viewed_profiles do |t| t.integer :profile_id t.integer :viewed_profile_id end endend修改此外,当我去我的控制台和I型ViewedProfile没有出现。任何想法,为什么? = C的模式通常应该出现!editAlso when I go to my console and I type ViewedProfile nothing comes up. Any idea as to why? =c the schema should normally show up!推荐答案首先,你的条件的 型号 名之间迷糊中 属性(特别是外键) 。型号将拥有的属性和协会将设置为型号Firstly, you are confused in between the terms Model names and attributes(specially Foreign keys).Model will have attributes and the associations will be set to models.您必须设置你的模型像这样You have to set your models like thisclass ViewedProfile < ActiveRecord::Base has_one : profileendClass Profile < ActiveRecord::Basebelongs_to :viewed_profilevalidates :viewed_profile_id, presence: truevalidates :viewed_profile_id, uniqueness: trueend和你相应的迁移文件应该是这样的。And your corresponding migration files should look like thisclass CreateViewedProfile < ActiveRecord::Migration def change create_table :viewed_profiles do |t| t.string :name end endendclass CreateProfile < ActiveRecord::Migration def change create_table :profiles do |t| t.integer :viewed_profile_id end endend我会建议开始之前阅读这些指南的文章。I would recommend to read these Guides articles before getting started. 协会Associations 迁移Migrations 验证Validations 这篇关于创建并在执行HAS_ONE关系轨关系型数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-21 15:52