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.
質問
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.
Edit:
interest_hashes.inspect
output example:
[{"category"=>"Interest", "name"=>"Formula One"}, {"category"=>"Musical instrument", "name"=>"Guitar"}]
解決
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.