复选框值未通过关联

时间:2016-05-08 13:21:46

标签: ruby-on-rails simple-form nested-attributes has-many-through strong-parameters

对于我的房间编辑表单,我试图通过与相同模型(颜色和房间)的关系来关联2个has_many

我的联接模型迁移在哪里:

color_preferences

class CreateColorPreferences < ActiveRecord::Migration
  def change
    create_table :color_preferences do |t|
      t.references :color
      t.references :room
      t.string :value

      t.timestamps null: false
  end
end

列“值”可以包含以下值:

我有以下模型与当前的关系:

room.rb

class Room < ActiveRecord::Base
   has_many :color_preferences
   has_many :colors, through: :color_preferences
   accepts_nested_attributes_for :color_preferences
end

color.rb

class Color < ActiveRecord::Base

  has_many :color_preferences
  has_many :rooms, through: :color_preferences
end

和我的联合模式:

color_preference.rb

class ColorPreference < ActiveRecord::Base

  belongs_to :color
  belongs_to :room

end

我的控制员:

rooms_controller.rb:

class RoomsController < ApplicationController

  before_action :set_room, only: :edit

  def edit
    @love_colors = if @room.color_preferences.where(value: "love").present?
      @room.color_preferences.where(value: "love")
    else
      @room.color_preferences.build
    end
    @hate_colors = if @room.color_preferences.where(value: "hate").present?
      @room.color_preferences.where(value: "hate")
    else
      @room.color_preferences.build
    end
  end

  private

  def set_room
    @room = Room.find(params[:id])
  end

  def room_params
    params.require(:room).permit(color_preferences_attributes: [:id, :value, color_id: []])
  end
end

和我的观点:

室/ edit.html.haml

= simple_form_for @room do |f|
  = f.simple_fields_for :color_preferences, @love_colors do |cp|
    = cp.association :color, as: :check_boxes
    = cp.hidden_field :value, value: "love"
  = f.simple_fields_for :color_preferences, @hate_colors do |cp|
    = cp.association :color, as: :check_boxes
    = cp.hidden_field :value, value: "hate"

如果我查看参数,我有以下内容:

"room"=>{"color_preferences_attributes"=>{"0"=>{"color_id"=>["11", "12", "13", ""], "value"=>"love"}, "1"=>{"color_id"=>["1", "2", "3", ""], "value"=>"hate"}}

但ColorPreferences表中没有保存颜色:

[#<ColorPreference id: 1, color_id: nil, room_id: 1, value: "love", created_at: "2016-05-08 12:55:29", updated_at: "2016-05-08 12:55:29">...]

我的两个问题是:

  • 我的设置没有保存color_id值有什么问题?
  • 我是否正确设置了编辑方法以检索表单中的颜色值?实际上如果我为特定条目设置了颜色ID,我没有得到选择的值。 谢谢=)

1 个答案:

答案 0 :(得分:0)

在您的属性中,您需要在参数中发送color_ids而不是color_id

事实上,如果您直接从colors引用@room关联,那么您的表单代码可以变得更加简单:

= simple_form_for @room do |f|
  = f.input :color_ids, as: :check_boxes, collection: @love_colors, value_method: :id, label_method: :value