Mik
Mik

Reputation: 1703

What is the best way to merge 2 tables with Active Record and Mysql

We need to allow users to customize their entities like products... so my intention was to have a product table and a custom_product table with just the information the users are allowed to change.

When a client goes to the product I want to merge the information, means I want to merge the two tables - the custom overwrites the default Products table.

I know that in mysql there exists a ifnull(a.title, b.title) way but I was wondering if there is any nice and efficient way to solve this in Rails 4 with Active Record. Assume that the products and custom products table have just 2 columns, ID and TITLE

Upvotes: 1

Views: 203

Answers (1)

marzapower
marzapower

Reputation: 5611

I think you can convert both objects to JSON and then handle their params as a hash, using the merge method:

class Product
end

class Customization
  belongs_to :product
end


a = Product.find(...)
b = a.customization

c = JSON(a.to_json).merge(JSON(b.to_json).reject!{|k,v| v.nil?})

Therefore c will contain all params from Product eventually overridden by those in Customization which are not nil.

If you still want to use a Product object with hybrid values (taken from Customization) you can try this:

a.attributes = a.attributes.merge(b.attributes.reject!{|k,v| v.nil?})

In this case a will still be a Product instance. I would recommend to keep the same attributes in both models when doing this.

Upvotes: 1

Related Questions