【问题标题】:How to get the checked boxes with link_to into params?如何将带有 link_to 的复选框放入参数中?
【发布时间】:2018-11-27 21:50:13
【问题描述】:

我有一个带有电影和类别的 Rails 5.2.1 应用程序。它们通过连接表的has_and_belongs_to_many 关系相互连接。

尝试执行以下操作:在电影的 index 页面上,我想过滤通过选中类别复选框显示的电影集合。我可以正确显示类别的复选框,但我很难获得有关哪些复选框被选中到参数中的信息。

/ rails_app/app/views/movies/index.html.slim
h1 Listing movies

= collection_check_boxes(@movies, :category_ids, Category.all, :id, :name) do |box|
  = box.check_box
  = box.label

= link_to 'Filter movies on category', params.permit!.merge(filter: :category_ids)

table
  / table with movies that will be filtered

这些:category_ids 似乎是错误的。是否有可能以这种方式获得复选框结果(用于进一步过滤查询字符串参数)?我错过了什么吗,例如在我的控制器中?

# rails_app/app/controllers/movies_controller.rb
class MoviesController < ApplicationController
  def index
    @movies = Movie.all
  end

...

  def movie_params
    params.require(:movie).permit(:name, :rating, category_ids: [])
  end
end

以上是一个示例应用程序,由一些脚手架和一些编辑生成:

rails generate scaffold category name:string
rails generate scaffold movie name:string rating:integer
rails generate migration CreateJoinTableMoviesCategories movie category
bin/rails db:migrate RAILS_ENV=development
-> 将has_and_belongs_to_many :movies 添加到类别类
-> 将has_and_belongs_to_many :categories 添加到电影类
-> 将category_ids: [] 添加到电影类中的movie_params

【问题讨论】:

  • 试试params.require(:movie).permit(:name, :rating, :category_ids =&gt; [])

标签: ruby-on-rails slim-lang


【解决方案1】:

试试这个,看看它是否适合你。

查看:

    / rails_app/app/views/movies/index.html.slim

    = form_for :movie do |f|
     = f.collection_check_boxes(:category_ids, Category.all, :id, :name) do |box|
      = box.check_box
      = box.label
     = f.submit

    / table with movies that will be filtered

控制器:

# rails_app/app/controllers/movies_controller.rb
class MoviesController < ApplicationController
  def index
    @movies = if params[:movie]
                Movie.joins(:categories).where(categories: { id: params[:movie][:category_ids] })               
              else
                Movie.all
              end
  end
  ... 

基本上,将复选框包装在表单中,然后在存在过滤器参数时调整 index 操作。

注意:我不熟悉苗条的语法,如果遇到语法错误,请调整它:)。

【讨论】:

  • 感谢您的回答,这给了我一些新的想法! (我试图看看它是否可以在没有form_for 的情况下完成,但最终可能会使用它。)
  • 其他选项是在单击过滤器链接时触发页面刷新,但您需要一些 javascript 才能工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
相关资源
最近更新 更多