model自定义属性
model不存在属性自定义
class Blog < ActiveRecord::Base
def one_string= tags
tags.split(",").each do |tag|
one_tag = find_by (title: tag)
one_tag = Tag.new(title: tag) unless one_tag
self.tags << one_tag
end
end
end
model已有属性自定义
class Blog < ActiveRecord::Base
def content= one_content
self.content= one_content * 2
end
end
上面的写法会造成死循环的,如果是已有属性不可以这么定义.正确写法如下
def content= one_content
write_attribute :content, one_content * 2
end
model通过attr_accessor定义
class Blog < ActiveRecord::Base
attr_accessor :custom_field
end