创建并在执行HAS_ONE关系轨关系型数据库 [英] Creating and enforcing has_one relationship in rails relational database
问题描述
在工作中看到的配置文件表。那种我有一个问题设置它,这是正确的?我感到困惑的的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_id
end
迁移
class CreateViewedProfile < ActiveRecord::Migration
def change
create_table :viewed_profiles do |t|
t.integer :profile_id
t.integer :viewed_profile_id
end
end
end
修改
此外,当我去我的控制台和I型ViewedProfile没有出现。任何想法,为什么? = C的模式通常应该出现!
edit
Also 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!
推荐答案
首先,你的条件的 型号
名之间迷糊中< STRONG> 属性(特别是外键)
。型号将拥有的属性和协会将设置为型号
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 this
class ViewedProfile < ActiveRecord::Base
has_one : profile
end
Class Profile < ActiveRecord::Base
belongs_to :viewed_profile
validates :viewed_profile_id, presence: true
validates :viewed_profile_id, uniqueness: true
end
和你相应的迁移文件应该是这样的。
And your corresponding migration files should look like this
class CreateViewedProfile < ActiveRecord::Migration
def change
create_table :viewed_profiles do |t|
t.string :name
end
end
end
class CreateProfile < ActiveRecord::Migration
def change
create_table :profiles do |t|
t.integer :viewed_profile_id
end
end
end
我会建议开始之前阅读这些指南的文章。
I would recommend to read these Guides articles before getting started.
Associations
Migrations
Validations
这篇关于创建并在执行HAS_ONE关系轨关系型数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!