Search code examples
ruby-on-railsactiverecordruby-on-rails-4

Creating and enforcing has_one relationship in rails relational database


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!


Solution

  • 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