简体   繁体   English

Rails attr_accessor和attr_writer

[英]Rails attr_accessor and attr_writer

newbie alert 新手警报

I'm watching one of Ryan Bate's RailsCasts on virtual attributes. 我正在观看Ryan Bate关于虚拟属性的RailsCasts之一。 He's adding tags to an article on a blogging platform. 他正在为博客平台上的文章添加标签。 http://media.railscasts.com/assets/episodes/videos/167-more-on-virtual-attributes.mp4 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? 我的问题是,你能否解释一下将它从attr_accessor更改为attr_accessorattr_writer以及他添加的方法? 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) (注意,我已经阅读了有关attr_accessor和attr_writer的文档,但它仍然没有点击,所以我不知道为什么他在创建该方法时进行此更改)

attr_accessor: :tag_names creates these two methods: attr_accessor: :tag_names创建这两个方法:

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 . 因为Ryan有自己的tag_names (“reader”)方法,所以他不需要使用attr_accessor动态创建它。 He needs only the ("writer") method which is created by attr_writer . 他只需要由attr_writer创建的(“writer”)方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM