This time, I implemented the hashtag function in rails. https://glodia.jp/blog/3936/ I referred to the site of.
Completion drawing If you add a tag when listing an item
You can check the hashtag that you can follow the link at the time of posting details,
Products with the same tag are lined up at the end of the link
Implementation method 1 Product table items and tag table tags are connected by an intermediate table 2 Write a description in the helper to link the tag name.
items_helper.rb
def render_with_hashtags(tag_name, tag_id)
tag_name.gsub(/[##][\w\p{Han}Ah-Gae-゚]+/){|word| link_to word, "/item/hashtag/#{word.delete("#")}?tag_id=#{tag_id}"}.html_safe
end
The name of the tag is passed as the first argument, and the id of the tag stored in the intermediate table is passed as the second argument. By replacing it with url with the gsub method and adding the html_safe method, you can avoid escaping and you can follow the link in the form of "# name" in the view. In the description of? tag_id = # {tag_id}, put the id of the tag in the link
3 Routing implementation
routes.rb
get '/item/hashtag/:name', to: "items#hashtag"
I think it's best to nest inside the item controller
4 Controller implementation
items_controller.rb
def hashtag
@tag = Tag.find(params[:tag_id])
@items = @tag.items
end
Pass the tag_id prepared in the link in 2 with params and search for the corresponding tag Put the product with the corresponding tag in the variable
5 Implement the view using @items for each method as when creating the post details list
done!
Recommended Posts