This time, the product name (name) and product description (description) saved in the items table A keyword from the tag name (tag _name) values stored in the tags table I want to create an implementation of a searchable function. (The items table and the tags table are associated using an intermediate table in a many-to-many relationship.)
Create your own method in 1 item model, define the search conditions from each table and assign them to variables (@item, @sescription and @tag) 2 Create an empty array and assign it to a variable (@items) 3 Get it as one element by applying each method and add it to the array. (As for tags, one product may have multiple tags, so double each is applied.) 4 Use the uniq method to remove the overlapping elements. (Example: When you search for "apple", if the keyword "apple" is included in both the product name @item and the product description @description, the same product will be included in the array @items. Because) 5 Finally, explicitly describe the return value and send the data to params (@items)
item.rb
def self.item_search(search)
if search != ""
@item = Item.where('name LIKE(?)', "%#{search}%")
@description = Item.where('description LIKE(?)', "%#{search}%")
@tag = Tag.where('tag_name LIKE(?)', "%#{search}%")
@items = []
@item.each do |i|
@items << i
end
@description.each do |d|
@items << d
end
@tag.each do |t|
t.items.each do |ta|
@items << ta
end
end
@items = @items.uniq
return @items
else
return nil
end
end
end
6 Call the "item_search method" created in the model earlier with the controller.
items-controller.rb
def item_search
@items = Item.item_search(params[:keyword])
end
7 Extract the elements contained in the array @items using the each method.
item_search.html
<% @items.each do |i| %>
<% =i.name%>
[Omitted]
<% end %>
Recommended Posts