0

I have a ruby method that returns multiple records with 7 columns. I want to insert these records to the other table which has more than 15 columns.

How can I use the ActiveRecord Create method in my model to insert those records to match exactly into the new table which has the same column name.

Ex:

I have a model method like the following:

def self.record_letter_group
  .....
end

In the console, when i try to run this method, it returns the following records

([#<Letter::Group User_ID: "sri", Code: "12345", Group_ID: 15>, 
  #<Letter::Group User_ID: "sri", Code: "12445", Group_ID: 15>,
  #<Letter::Group User_ID: "sri", Code: "12545", Group_ID: 15>,
  #<Letter::Group User_ID: "sri", Code: "12645", Group_ID: 15>,
  #<Letter::Group User_ID: "sri", Code: "12745", Group_ID: 15>,
])

I want to do something like,

save_records = Letter::Category.create(record_letter_group)

Note: This Letter::Category has 15 columns

Thanks

1 Answer 1

1

It should look something like this:

# whitelist the attributes you want to save to "categories" table
valid_attributes = [ :User_ID, :Code, :Group_ID ]


record_letter_group_attributes = record_letter_group.map { |group| group.attributes.slice(*valid_attributes) }

save_records = Letter::Category.create(record_letter_group_attributes)
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you. Can you explain the *valid_attributes please?
And, group.attributes return the set of values. But group.attributes.slice(*valid_attributes) returns {}
yep, the valid_attributes is supposed to be a white list of column names (attributes). For example, if Letter::Group has [ :id, :name, :description ] attributes but you only want [ :name, :description ] to be saved to Letter::Category, slice(:name, :description) would extract only :name and :description attributes (and remove an :id attribute)
meaning, you should populate the valid_attributes array with attributes you want, because you might want to skip some (like :id, :updated_at, :created_at) etc
Thank you. I don't have any other columns. Because I am using joins to select this columns. So I want to insert the selected columns to Letter::Category(Letter::Category has 15 columns. I need to select the exact column names and insert the values.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.