5
votes

newbie alert

I'm watching one of Ryan Bate's RailsCasts on virtual attributes. He's adding tags to an article on a blogging platform. http://media.railscasts.com/assets/episodes/videos/167-more-on-virtual-attributes.mp4

At one point he has working code

attr_accessor :tag_names

In this example, the tag names do not appear in the form if they validate, so he changes the name of the attribute, and adds a method so that the tag names persist if there's a validation error on a different field

attr_writer :tag_names



def tag_names
    @tag_names || tags.map(&:name).join(' ')
end

My question is, can you please explain the significance of changing it from attr_accessor to attr_writer in combination with the method he added? Why did he need to change the attribute name when he added that method?

(note, i have read documentation about attr_accessor and attr_writer, but it's still not clicking enough so I'm not getting why he's making this change when he creates that method)

1

1 Answers

13
votes

attr_accessor: :tag_names creates these two methods:

def tag_names
  @tag_names 
end

and

def tag_names=(value)
  @tag_names=value
end

Because Ryan has his own tag_names ("reader") method he doesn't need to dynamically create it with attr_accessor. He needs only the ("writer") method which is created by attr_writer.