Question

I'm was trying to add multiple objects like so:

class Person < ActiveRecord::Base
  has_many :interests
  ...

  def add_interests(interest_hashes)
    interest_hashes.each do |interest|
      Rails.logger.debug "person.apply_interests: interest: #{interest.inspect}"
      interests.build(:name => interest.name, :category => interest.category)
    end
    save!
  end
  ...
end

However in the log when calling <some person>.add_interests(<some hashes>) all I see is the first hash - no error or exception. If I remove the build method the loop works as expected.

  1. What is happening when calling the build method?
  2. What's a better way to achieve what I'm trying?

Edit:

interest_hashes.inspect output example:

[{"category"=>"Interest", "name"=>"Formula One"}, {"category"=>"Musical instrument", "name"=>"Guitar"}]
Was it helpful?

Solution

You should get a NoMethodError when calling name and category on interest, since hashes are accessed using the [] method. Replace

interest.name

with

interest["name"]

Or use an Struct, which may be preferable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top