Has_many with model name as foreign key

Hi,

It’s possible to do this :

models:

  • product has_many attributes
  • user has_many attributes
  • other_model has_many attributes

model attribute belongs to

  • product , but the foreign_key is not product_id but the mode name
    (Product) stored in table attributes(id, name, model)
  • user , but the foreign_key is not product_id but the mode name
    (Product) stored in table attributes(id, name, model)

I want associate the attributes model with whole model and not with
single
record.

thx

Hi,

Fistly, dont create a model with the name “Attribute”. Some of the rails
core methods uses “attributes” . Use something like “custom_attributes”
.

Next, to make a model belong_to different models on the same
foreign_key,
Make sure you use polymorphic-associations
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
in rails.

thx,

but with polymorphic associations, i always need to set a foreign key
column,

my need is to set only the column type (model name)…

class Picture < ActiveRecord::Base
belongs_to :imageable, polymorphic: true

#table pictures (id, name, imageable_id, imageable_type)

how use it without imageable_id

end

class Employee < ActiveRecord::Base
has_many :pictures, as: :imageable
end

class Product < ActiveRecord::Base
has_many :pictures, as: :imageable
end

Le samedi 27 décembre 2014 17:00:35 UTC+1, Vivek S. a écrit :

On 27 December 2014 at 16:19, fmh [email protected] wrote:

thx,

but with polymorphic associations, i always need to set a foreign key
column,

my need is to set only the column type (model name)…

Explain the problem that you are trying to solve with this unusual
scheme. It may well be that there is a better way of solving it.

Colin

i have many model that user want add or remove attribute dynamically

example :

table / model : product (id, name, price, metadata (serialized column ,
hash) )
table /mode : other_model (id, name, xxx_attribute, , metadata
(serialized
column , hash) )

table / model : my_custom_fields (id, name , field_type , model (column
contain model name) )

form and fields view are generate dynamically (with partial)

i can do it by :

class product < AR::Base
serialize :metadata , Hash

#i save all my custom attributes in metadata column

def get_all_custom_attributes
My_custom_field.find_by_model(self.class.name)
end

end

but i need a properly way if there is one :wink:

Le samedi 27 décembre 2014 17:54:13 UTC+1, Colin L. a écrit :