Creating and enforcing has_one relationship in rails relational database

╄→гoц情女王★ 提交于 2020-01-05 14:25:53

问题


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.

Does this look correct, also is there a way to enforce the relation in ActiveRecord?

model

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

migration

class CreateViewedProfile < ActiveRecord::Migration
  def change
    create_table :viewed_profiles do |t|
      t.integer :profile_id
      t.integer :viewed_profile_id
    end
  end
end

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!


回答1:


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



来源:https://stackoverflow.com/questions/23259059/creating-and-enforcing-has-one-relationship-in-rails-relational-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!