ruby on rails - Assign a value to an active record relation field -


this first model :

class sender < applicationrecord     has_many :letters end 

and second one:

class letter < applicationrecord   belongs_to :sender end 

i find letter in rails consol :

@letter = letter.where(id: 378) 

the result :

#<activerecord::relation [#<letter id: 378, indicator: "95/2", classification: "aa", urgency: "aa", package_id: nil, registrar_id: 0, user_id: nil, subset_type: "official", created_at: "2016-11-10 06:02:14", updated_at: "2016-11-10 06:02:14", sender_id: nil>]> 

as can see sender_id nil. thing want set value sender_id :

@letter.sender_id = 12 

but got error:

nomethoderror: undefined method `sender_id=' #<letter::activerecord_relation:0x00000004cc96c0> did mean?  send_later     /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/relation/delegation.rb:123:in `method_missing'     /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/relation/delegation.rb:93:in `method_missing'     (irb):19     /var/lib/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/console.rb:65:in `start'     /var/lib/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/console_helper.rb:9:in `start'     /var/lib/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:78:in `console'     /var/lib/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'     /var/lib/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `<top (required)>'     bin/rails:4:in `require'     bin/rails:4:in `<main>' 

what's wrong?

letter.where(id: 378) 

returns collection of records matching query condition. , of course, not have method sender_id= activerecord::relation object.

what want instead single record, can either

@letter = letter.where(id: 378).first 

or

@letter = letter.find(id: 378) 

now, having single record, can update it's sender_id attribute:

@letter.update(sender_id: 12) 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -