I'm going through the "Tags" section of the Blogger tutorial and am a bit confused on one part: the def to_s function (in tag.rb); why it's required and how it's included.
I've included some relevant parts of relevant files for context.
MODELS
article.rb
class Article < ActiveRecord::Base
attr_accessible :tag_list
has_many :taggings
has_many :tags, through: :taggings
def tag_list
return self.tags.collect do |tag|
tag.name
end.join(", ")
end
def tag_list=(tags_string)
self.taggings.destroy_all
tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
tag_names.each do |tag_name|
tag = Tag.find_or_create_by_name(tag_name)
tagging = self.taggings.new
tagging.tag_id = tag.id
end
end
end
tag.rb
class Tag < ActiveRecord::Base
has_many :taggings
has_many :articles, through: :taggings
def to_s
name
end
end
tagging.rb
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :article
end
CONTROLLERS
tags_controller.rb
class TagsController < ApplicationController
def index
@tags = Tag.all
end
def show
@tag = Tag.find(params[:id])
end
def destroy
@tag = Tag.find(params[:id]).destroy
redirect_to :back
end
end
HELPERS
articles_helper.rb
module ArticlesHelper
def tag_links(tags)
links = tags.collect{|tag| link_to tag.name, tag_path(tag)}
return links.join(", ").html_safe
end
end
VIEWS
new.html.erb
<%= form_for(@article, html: {multipart: true}) do |f| %>
<p>
<%= f.label :tag_list %>
<%= f.text_field :tag_list %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
show.html.erb
Tags: <%= tag_links(@article.tags) %>
I got your point. When you concatenate value in string you have to write eg
"hello #{@user.name}"
So instead of calling @user.name u can specify whatever u have to display user as a string you can directly specify in to_s method so that you dont need to call .to_s again just write
"hello #{@user}"
above line of code search for .to_s method for @user's class and print returning value.
same is for routing like
user_path(@user)
will give you >> users/123 # where 123 is id of @user
if you write
def to_params
self.name
end
Then it will give >> users/john # where john is the @user's name
to_s is the standard Ruby method for converting an Object into a string. You define to_s when you want a custom string representation for your class. Example:
1.to_s #=> "1"
StandardError.new("ERROR!").to_s #=> "ERROR!"
And so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With