Search code examples
ruby-on-railsrelationshipnomethoderror

Relationship clasess has attribute error


Why relationship classes attribute is not attribute?

$ 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>

Model:

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

  # Validations
...
end

Solution

  • It is just because your are calling the #attributes= instance method on the class ResourceServer and not on the object rs.

    What you want to do is:

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

    And it will work! :)