Ruby on Rails Friday, December 7, 2012

On Dec 7, 2012, at 4:11 AM, Colin Law wrote:

> On 7 December 2012 01:30, renu mehta <lists@ruby-forum.com> wrote:
>> Hello,
>>
>> If I have a model A as :
>>
>> name
>> address
>> phone
>>
>> and model B as:
>>
>> name
>> address
>> email
>
> My first suggestion would be that maybe the database design could be
> improved. If there are tables with common fields then possibly the
> common data should be moved to a separate table, or perhaps even the
> two original tables should be merged. It is a nightmare trying to
> keep tables with common data in sync.
>
> Colin

I agree with Colin. However, if you have a specific need (such as data conversion), then you can do something like:

irb1.9.3> JudgedEvent.column_names
#1.9.3 => ["id", "number", "name", "created_at", "updated_at", "year", "event_description_id"]
irb1.9.3> EventDescription.column_names
#1.9.3 => ["id", "name", "name_for_certificate", "description", "created_at", "updated_at"]
irb1.9.3> cols = EventDescription.column_names - %w[ id created_at updated_at ]
#1.9.3 => ["name", "name_for_certificate", "description"]
irb1.9.3> JudgedEvent.first.attributes.slice(*cols)
JudgedEvent Load (0.8ms) SELECT "judged_events".* FROM "judged_events" LIMIT 1
#1.9.3 => {"name"=>"Financial Analyst Team"}

Note that there are columns in EventDescription (like 'email' in your 'B' above) that are not present in JudgedEvent (your 'A'), but slice'ing them doesn't affect the attributes hash that will be passed on to the .new method. The "extra" columns in the destination that are missing from the source are effectively ignored, but if the source ever expands to include any of them, then they will be automagically* included.

-Rob

*(no actual magic involved)

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment