关系clasess有属性错误

时间:2011-08-31 13:13:02

标签: ruby-on-rails relationship nomethoderror

为什么关系类属性不是属性?

$ rs = ResourceServer.new
 => #<ResourceServer id: nil, resource_id: nil, server_id: nil, created_at: nil, updated_at: nil> 

$ rs = ResourceServer.attributes = {:server_id => 1, :resource_id => 1}
 NoMethodError: undefined method `attributes=' for #<Class:0x00000003384728>

型号:

class ResourceServer < ActiveRecord::Base
  belongs_to :server
  belongs_to :resource

  # Validations
...
end

2 个答案:

答案 0 :(得分:3)

这只是因为您在类#attributes=上调用ResourceServer实例方法而不是在对象rs上调用。

您想要做的是:

rs.attributes = {:server_id => 1, :resource_id => 1}

它会起作用! :)

答案 1 :(得分:0)

ResourceServer是一个类,您需要该类的实例才能为其分配属性。例如,你可以这样做:

rs = ResourceServer.new
rs.attributes = {:server_id => 1, :resource_id => 1}