Achaius
Achaius

Reputation: 6124

How to update a single field in has_many object

I am having a user object which has one-to-many relation with Address object. My class looks like this

class User
  has_many :address
end

class Address
  belongs_to :user
end

I want to update only city column in address table for a particular user. How to do this?

I tried like this

@user.address.each do |a|
  a.city = 'Alabama'
end
@user.save

But this is not working.

Upvotes: 1

Views: 445

Answers (2)

Soundar Rathinasamy
Soundar Rathinasamy

Reputation: 6728

This should work.

@user.address.update_all(:city => 'Albama')

Upvotes: 2

Mike
Mike

Reputation: 1042

a.update_attributes(:city => 'Alabama')

Upvotes: 2

Related Questions