fmh
(fmh)
December 27, 2014, 1:17am
1
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 in rails.
fmh
(fmh)
December 27, 2014, 4:19pm
3
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
``
Colin_Law
(Colin Law)
December 27, 2014, 4:53pm
4
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
fmh
(fmh)
December 27, 2014, 5:11pm
5
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