如何在 rails 中使用 filterrific gem?
How to use filterrific gem in rails?
我已经使用filterrific
gem过滤了rails中的模型。
目前,我有三个模型,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})}
因为很难用tag.name
做过滤(见Whosebug),所以我用tag_id
in join table tagging
做过滤器。
Tagging.rb
belongs_to :video
belongs_to :tag
Tag.rb
has_many :taggings
has_many :videos, through: :taggings
目前,scope
正在运行,但我不知道如何编写controller和view
在控制器中:如何写select_options
方法?
在视图中:select
方法怎么写?目前,我是这样写的,但没有用:
f.select(:by_tag, Tag.all, { include_blank: '- Any -' }, :class=>'form-control')
进入 select
标签助手的 select 选项需要看起来像一对数组 [ [ name, id ], [ name, id ] ... ]
。尝试这样的事情:
f.select(:by_tag, Tag.all.map {|tag| [tag.name, tag.id]}, { include_blank: '- Any -' }, :class=>'form-control')
或者为了让事情变得更干净,你可以使用 rails collection_select
帮助程序,比如
f.collection_select(:by_tag, Tag.all, :id, :name, prompt: '- Any -', class: 'form-control')
第二个需要根据您的控制器使用空白选项执行的操作进行调整。
上有很好的例子
我已经使用filterrific
gem过滤了rails中的模型。
目前,我有三个模型,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})}
因为很难用tag.name
做过滤(见Whosebug),所以我用tag_id
in join table tagging
做过滤器。
Tagging.rb
belongs_to :video
belongs_to :tag
Tag.rb
has_many :taggings
has_many :videos, through: :taggings
目前,scope
正在运行,但我不知道如何编写controller和view
在控制器中:如何写select_options
方法?
在视图中:select
方法怎么写?目前,我是这样写的,但没有用:
f.select(:by_tag, Tag.all, { include_blank: '- Any -' }, :class=>'form-control')
进入 select
标签助手的 select 选项需要看起来像一对数组 [ [ name, id ], [ name, id ] ... ]
。尝试这样的事情:
f.select(:by_tag, Tag.all.map {|tag| [tag.name, tag.id]}, { include_blank: '- Any -' }, :class=>'form-control')
或者为了让事情变得更干净,你可以使用 rails collection_select
帮助程序,比如
f.collection_select(:by_tag, Tag.all, :id, :name, prompt: '- Any -', class: 'form-control')
第二个需要根据您的控制器使用空白选项执行的操作进行调整。
上有很好的例子