MiH
MiH

Reputation: 421

Why can't I update has_many :through association in rails 4

My project is about an online shopping site, using Ruby on Rails to buy phones. Now i'm trying to create Basket for Users.

class User < ActiveRecord::Base
  has_many :baskets
  has_many :phones, :through => :baskets
end

class Phone < ActiveRecord::Base
  has_many :baskets
  has_many :users , :through => :baskets
end

class Basket < ActiveRecord::Base
  belongs_to :user
  belongs_to :phone
end

When i update like that:

Phone.baskets.where(user_id:1).update(name:"abc")

It's wrong! I dont know why it doesn't work.

Upvotes: 1

Views: 1421

Answers (2)

dwenzel
dwenzel

Reputation: 1434

First off, as @Austio's answer pointed out, you need to use the association method on an instance of a class, not the class itself. So: <specific instance of Phone>.baskets instead of Phone.baskets.

Secondly, if you are looking to update all of the objects of a collection with the same attribute, you need to use update_all. So, let's say that phone is a specific Phone object. Then you would want:

phone.baskets.where(user_id:1).update_all(name:"abc")

The update method is designed to either update the attributes of one single object, or update an array of multiple objects with an array of separate attribute hashes: http://apidock.com/rails/ActiveRecord/Base/update/class

Upvotes: 0

Austio
Austio

Reputation: 6095

These two different things, Class vs Instance.

Phone is a class but the relationship of baskets belongs on an instance of that class.

So something like this should allow you to use the relation

instance_of_phone = Phone.first
instance_of_phone.baskets.where(user_id: 1).update(name: 'abc')

Another way is to access directly

Basket.find_by(user_id: 1, basket_id: 1).update(name: 'abc')

Upvotes: 1

Related Questions