【问题标题】:How to pass value of multiple checkbox to a model?如何将多个复选框的值传递给模型?
【发布时间】:2019-11-12 23:16:39
【问题描述】:

我在 Rails 中形成了多个复选框值。 我需要将此值(如果选中)传递给创建类别的模型。

我在 form.html_erb 中有这个

<%= form.check_box :categories, {multiple: true}, "U6", nil %>
<%= form.check_box :categories, {multiple: true}, "U8", nil %>
<%= form.check_box :categories, {multiple: true}, "U10", nil %>

我想创建带有选中值的 TeamCategory。 像这样?

def create_tournament_team_categories
    VALUE_CHECKED.each do |name|
      team_category = TeamCategory.where(name: VALUE_CHECKED).first_or_create
      self.tournament_team_categories << TournamentTeamCategory.create(team_category: team_category)
    end
  end

现在 TeamCategory 是自动创建的:

    def create_tournament_team_categories TeamCategory::NAMES.each do |name| 
team_category = TeamCategory.where(name: name).first_or_create 
self.tournament_team_categories << TournamentTeamCategory.create(team_category: team_category)
    end 
    end

在 TeamCategory 模型中,我: NAMES = %w[U6 U8 U10 U12 U14 U16].freeze

【问题讨论】:

    标签: ruby-on-rails checkbox


    【解决方案1】:

    使用collection_check_boxes 助手:

    form.collection_check_boxes(:category_ids, TeamCategory.all, :id, :name)
    

    _ids= 是一个特殊的 setter created by the has_many and HABTM macros。您只需传递一个 id 数组,rails 将为您创建连接记录。

    只要确保将数组列入白名单即可:

    params.require(:tournament).permit(:foo, :bar, category_ids: [])
    

    【讨论】:

    • 类别名称不保存在任何表中。我想手动传递 :name 值,然后将 Team Category 创建为选中的值。
    • 现在 TeamCategory 是自动创建的:``` def create_tournament_team_categories TeamCategory::NAMES.each do |name| team_category = TeamCategory.where(name: name).first_or_create self.tournament_team_categories
    • 这听起来像是一个简单问题的非常复杂的解决方案。如果您真的想使用普通数组,请使用复选框助手并通过命名复选框 tournament[category_ids][] 在参数中创建一个数组。
    猜你喜欢
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 2014-12-29
    • 2018-04-24
    • 1970-01-01
    相关资源
    最近更新 更多