pramod
pramod

Reputation: 2318

Buid two associations between two tables

I have a strange requirement in my project. Actually, I have two tables (users,galleries). I would like to access galleries table with has_one as well as has_many associations. The main purpose is to get the profile snap of the user by using has_one relation and to get the personally uploaded pictures by using has_many relation.

Initially I go with polymorphic association to resolve this (FYI, please find the below code snippet) .But I think it is not the right approach for this problem.

Would anybody explain how to handle this case in an efficient way.

class User < ActiveRecord::Base
  attr_accessible :name
  has_many :galaries, as: :imageable
  has_one :galary, as: :imageable
end

class Galary < ActiveRecord::Base
  attr_accessible :name
  belongs_to :imageable, polymorphic: true
end

Upvotes: 1

Views: 91

Answers (2)

tihom
tihom

Reputation: 8003

Can be done with scoped has_one association. Although not necessary, you can define which gallery is selected in the has_one using a scope. If no scope is given, the has_one would return the first match.

class User < ActiveRecord::Base
  attr_accessible :name
  has_many :gallaries
  has_one :gallery, -> { where primary: true }
end

class Gallery < ActiveRecord::Base
  #user_id, primary (boolean variable to select the gallery in has one association)
  attr_accessible :name
  belongs_to :user
end

Upvotes: 0

mohameddiaa27
mohameddiaa27

Reputation: 3597

You need to add a column user_id in galaries table in order to link the the user to the galary (profile snap).

rails generate migration add_user_id_to_galaries user_id:string 

This will generate the migration:

class AddUserIdToGalaries < ActiveRecord::Migration
  def change
    add_column :galaries, :user_id, :integer
  end
end

Then run rake db:migrate


Moving to our Models now:

class User < ActiveRecord::Base
  attr_accessible :name
  has_many :galaries, as: :imageable
  has_one :galary #profile snap
end

class Galary < ActiveRecord::Base
  attr_accessible :name
  belongs_to :imageable, polymorphic: true
  belongs_to :user #profile snap user
end

Upvotes: 1

Related Questions