如何将多个复选框的值传递给模型?

时间:2019-11-12 14:48:47

标签: ruby-on-rails checkbox

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

我在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

1 个答案:

答案 0 :(得分:1)

使用collection_check_boxes助手:

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

_ids=是一个特殊的设置器created by the has_many and HABTM macros。您只需传递一组ID,Rails就会为您创建连接记录。

只需确保将阵列列入白名单:

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