简体   繁体   English

为什么我不能更新has_many:通过Rails 4中的关联

[英]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. 我的项目是关于一个在线购物网站,使用Ruby on Rails购买电话。 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. 我不知道为什么它不起作用。

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')

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. 首先,正如@Austio的答案所指出的,您需要在类的实例上使用关联方法,而不是类本身。 So: <specific instance of Phone>.baskets instead of Phone.baskets . 因此: <specific instance of Phone>.baskets而不是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 . 其次,如果要更新具有相同属性的集合的所有对象,则需要使用update_all So, let's say that phone is a specific Phone object. 因此,假设phone是特定的Phone对象。 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 update方法旨在更新一个对象的属性,或使用一组单独的属性哈希更新多个对象的数组: http : //apidock.com/rails/ActiveRecord/Base/update/class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM