对于我的房间编辑表单,我试图通过与相同模型(颜色和房间)的关系来关联2个has_many
我的联接模型迁移在哪里:
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
端
列“值”可以包含以下值:
我有以下模型与当前的关系:
class Room < ActiveRecord::Base
has_many :color_preferences
has_many :colors, through: :color_preferences
accepts_nested_attributes_for :color_preferences
end
class Color < ActiveRecord::Base
has_many :color_preferences
has_many :rooms, through: :color_preferences
end
和我的联合模式:
class ColorPreference < ActiveRecord::Base
belongs_to :color
belongs_to :room
end
我的控制员:
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
和我的观点:
= 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">...]
我的两个问题是:
答案 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