0

am very new on rails development

Rails 3.2.13 / ruby 1.9.3

I have this model

class Post < ActiveRecord::Base
    attr_accessible :content, :title
    attr_accessor :testing

    def asignar
        title = "hey"
    end
end

And then when i go to the rails console:

irb(main):004:0* post = Post.new
=> #<Post id: nil, title: nil, content: nil, created_at: nil, updated_at: nil>
irb(main):005:0> post.asignar
=> "hey"
irb(main):006:0> post.title
=> nil

Is this normal?, do I have always to save the object so I can be able to get attributes?

4
  • 3
    self.title = 'hey'; title = "hey" is setting the local variable title, not the attribute.
    – Lee Jarvis
    Apr 16, 2013 at 18:55
  • 1
    As Lee says, when writing to an attribute of the model, you should use self.title. When reading the attribute it's customary to use only the attribute name title, but self.title or self[:title] would also work. Apr 16, 2013 at 18:57
  • Lee Jarvis that's exactly the answer, I know this is a very silly, still i think that could be useful for others, why dont you make your comment an answer so i can mark it as accepted :) thanks
    – Juan Jo
    Apr 16, 2013 at 18:59
  • Looks like hyngyn got there first. His answer is also correct, thanks though!
    – Lee Jarvis
    Apr 16, 2013 at 19:00

1 Answer 1

4

Try this:

def asignar
    self.title = "hey"
end

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.