NoMethodError - new since upgrading to Rails 4

会有一股神秘感。 提交于 2019-12-11 17:23:37

问题


I'm at my wit's end. I upgraded to Rails 4.2.10, and everything is terrible.

Here is the relevant part of /models/product.rb

class Product < ActiveRecord::Base
  delegate_attributes :price, :is_master, :to => :master

And here is /models/variant.rb:

class Variant < ActiveRecord::Base
  belongs_to :product

The variants table has fields for "price" and "is_master". Products table does not.

It used to be the case that one could access Product.price and it would get/set the price for the master variant (there's really only one variant per product, the way things are currently set up).

Now it complains that:

NoMethodError: undefined method `price=' for #<Product:0x0000000d63b980>

It's true. There's no method called price=. But why wasn't this an issue before, and what on earth should I put in that method if I create it?

Here's the code to generate a product in db/seeds.rb:

  product = Product.create!({
    name: "Product_#{i}",
    description: Faker::Lorem.sentence,
    store_id: u.store.id,
    master_attributes: {
      listing_folder_id: uuids[i],
      version_folder_id: uuids[i]
    }
  })

  product.price = 10
  product.save!
end

回答1:


delegate_attributes isn't a Rails method and looks like it comes from a gem (or gems) that aren't actively maintained?

If there's a new version of whatever gem you're using that might help, because the short answer is that part of the "delegating" of an attribute would involve getting and setting the attribute, so it would generate #price= for you.

If you want to define it yourself, this should do it (within your Product class):

def price=(*args)
  master.price=(*args)
end

or if you want to be more explicit:

def price=(amount)
  master.price = amount
end


来源:https://stackoverflow.com/questions/51953995/nomethoderror-new-since-upgrading-to-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!