Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a object from another object in rails

I want to create some records in my mysql database using some existing records. I am using rails 4.2

This is the relevat code in my controller:

linkconfig_id = 17
new_config = Linkconfigdetail.where(:linkconfig_id => user_params[:linkconfig_id])

new_config.each do |config|
  config[:linkconfig_id] = linkconfig_id
  config[:id] = nil
  config[:created_at] = nil
  config[:updated_at] = nil
end

Linkconfigdetail.create(new_config)

The new_config variable contains a few datasets of the Linkconfigdetail-model. I want to slightly change them and then save them as new, but I get the error message:

ArgumentError (When assigning attributes, you must pass a hash as an argument.): 

and the line of the create-method.

I already checked. The new_config-array is not nil. It is looking like this, before the create (using inspect):

#<ActiveRecord::Relation [#<Linkconfigdetail id: nil, linkconfig_id: 17, link_id: 1, location: 0, created_at: nil, updated_at: nil>, #<Linkconfigdetail id: nil, linkconfig_id: 17, link_id: 18, location: 1, created_at: nil, updated_at: nil>, #<Linkconfigdetail id: ...

I appreciate every hint, or any other solution to this problem in general. I can't imagine, that this is so difficult. I already had a lot of problems to even change the dataset. Many methods like delete didn't work, but I finally couldn't find a way to work around this issue.

like image 363
Christof Baumgartner Avatar asked Nov 04 '25 23:11

Christof Baumgartner


2 Answers

You can't pass a relation or other instance of that not a Hash for create. Instead, you can duplicate the original, creating a new instance not persisted with the same values as original (except id, created_at and updated_at attributes), and change the attributes you want before save it

you can do:

linkconfig_id = 17
configs = Linkconfigdetail.where(:linkconfig_id => user_params[:linkconfig_id])

configs.each do |config|
  new_config = config.deep_dup
  new_config.link_config_id = linkconfig_id

  new_config.save
end
like image 179
cefigueiredo Avatar answered Nov 07 '25 16:11

cefigueiredo


You are passing an object to create, whereas it should be a hash (but hey, it is exactly what error says, isn't it? ;))

So to get what you need, you could use attributes method:

new_config.each do |config|
  Linkconfigdetail.create(config.attributes)
end
like image 22
Andrey Deineko Avatar answered Nov 07 '25 16:11

Andrey Deineko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!