4

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.

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

There was a small typo: it is "linkconfig_id" and not "link_config_id". But beside of this, it worked like a charm. Many Thanks, you saved me a lot of time.
3

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

2 Comments

new_config is a relation, not an object
Thanks for your answer. I accepted the other one, because duplicating the original was was solving my problem a bit bettter. But attributes looks very useful and I am sure that I will need it soon.

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.