简体   繁体   中英

How to use filterrific gem in rails?

I have used filterrific gem to filter the model in rails.

Currently, I have three model, Video , Tagging , Tag

Video.rb

has_one :tagging
has_one :tag, through: :tagging

scope :by_tag, -> (tag_id) {joins(:tagging).where(taggings: {tag_id: tag_id})}

Because it's hard to use tag.name to do the filter(see StackOverflow ), so I use tag_id in join table tagging to do the filter.

Tagging.rb

belongs_to :video
belongs_to :tag

Tag.rb

has_many :taggings
has_many :videos, through: :taggings

Currently, the scope is working, but I don't know how to write controller and view

In controller: How to write select_options method?

In view: How to write select method? Currently, I write like this, but not working:

f.select(:by_tag, Tag.all, { include_blank: '- Any -' }, :class=>'form-control')

Your select options that go to the select tag helper need to look like an array of pairs [ [ name, id ], [ name, id ] ... ] . Try something like this:

f.select(:by_tag, Tag.all.map {|tag| [tag.name, tag.id]}, { include_blank: '- Any -' }, :class=>'form-control')

Or to keep things even cleaner, you could use the rails collection_select helper with something like

f.collection_select(:by_tag, Tag.all, :id, :name, prompt: '- Any -', class: 'form-control')

The second one many need tweaking depending on what your controller is doing with the blank option.

There are good examples on APIDock ActionView::Helpers::FormOptionsHelper#select .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM