Search code examples
ruby-on-railsrubyactiverecordruby-on-rails-5ruby-on-rails-6

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.


Solution

  • 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