【发布时间】:2016-09-03 04:12:48
【问题描述】:
对于我的房间编辑表单,我试图通过与相同模型(颜色和房间)的关系将 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
结束
“值”列可以有这些值:
- 爱
- 讨厌
我有以下模型与当前关系:
房间.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,我没有选择值。 谢谢 =)
【问题讨论】:
标签: ruby-on-rails simple-form nested-attributes has-many-through strong-parameters