quyen91 / toy-app-rubyonrail

simple demo for learning ruby on rails
0 stars 0 forks source link

Defining a Virtual Attribute #12

Open quyen91 opened 8 years ago

quyen91 commented 8 years ago

https://www.safaribooksonline.com/library/view/ruby-cookbook/0596523696/ch08s07.html

quyen91 commented 8 years ago

when using tag. It is better to using callback. like that

attr_accessor :tag_names
    after_save :assign_tags

    private
    def assign_tags
        if @tag_names
            self.tags = @tag_names.split(",").map do |name|
                # Tag.find_or_create_by_name(name)
                Tag.where(name: name.strip).first_or_create!
            end
        end
    end
    def list_tags
        self.tags.map(&:name).join(", ")
    end

it means that we only save tags if post is saved successfully.

quyen91 commented 8 years ago

other of after_save style

after_save do function_name
    # code here
end