【问题标题】:Relationship clasess has attribute error关系类有属性错误
【发布时间】:2011-08-31 13:13:02
【问题描述】:

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

$ 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

【问题讨论】:

  • 请将您的模型添加到您的问题中:)
  • 尝试添加 attr_accessible :server_id, :resource_id

标签: ruby-on-rails relationship nomethoderror


【解决方案1】:

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

你想做的是:

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

它会起作用的! :)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多