Reputation: 2661
Product model
Class Product < ActiveRecord::Base
belongs_to :product_group
end
ProductGroup model
Class ProductGroup < ActiveRecord::Base
has_many :products
end
Is the a way to declare a shortcut for product.product_group.name
as product.name
,
and have product_group.name
included in product.to_json
as name
whenever a Product is converted to json?
Upvotes: 0
Views: 143
Reputation: 35360
To answer your first question: create a name
method in Product
def name
product_group.name
end
As for your second question, you can customize as_json
, also in your Product
model. Something like this should work.
def as_json(options = {})
super.merge({ name: name })
end
Upvotes: 1