1

In a Ruby on Rails model class:

class DeliveryItem < ActiveRecord::Base
  attr_accessible :state
end

item=DeliveryItem.new
item.instance_variable_set "@name","apple"

NoMethodError: undefined method 'name' for #

How do I make this work?

2
  • use item.instance_variable_get "@name" Commented Mar 13, 2013 at 6:37
  • attr_accessible :state, :name Commented Mar 13, 2013 at 6:54

2 Answers 2

5

You can try this:

item.instance_variable_set(:@attributes, {'name' => 'apple'})
Sign up to request clarification or add additional context in comments.

Comments

1

The error means you don't have a name attribute for DeliveryItem. This means that there's no setter method for name or you don't have a name column. So to solve this issue, you have to either

  • add a name column or
  • create a setter method for name or
  • use attr_accessor or attr_writer to do the work for you

add the following to your model

class DeliveryItem < ActiveRecord::Base
  attr_accessor :name
end

then you should be able to use your code

item = DeliveryItem.new
item.instance_variable_set "@name","apple"

# or just use item.name=
item.name = 'apple'

1 Comment

thank u for the help, the attributes i want to set are not fixed:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.