我对rails非常陌生,在使用多个select时,我在更新关联表时遇到了一些问题。
我有三张表,portrait
portrait_tags
和tags
(标签存储我的标签名称(传统,鼓舞人心,社区等))
我希望的结果是'multiple select field'会根据Tag.all tag_id值将标签添加到portrait_tag表中。目前这似乎只插入一个字段,而portrait_tag表中的tag_id为NULL,然后当我返回编辑页面时,多个选择被复制。
PARAMS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"j+Obhq9u+mvOKYnj4+TAGy+be8s3AbZlMvuyKiot5iyKqjMyFAcs23PjbQjOTjwl6aRBx1M5lmYRZzTjOeDTJA==", "portrait"=>{"portrait_tags_attributes"=>{"0"=>{"tag_id"=>["", "1", "2"]}}}, "commit"=>"Save changes", "id"=>"72"}
Tag.rb
class Tag < ActiveRecord::Base
has_many :portraits, through: :portrait_tags
accepts_nested_attributes_for :portraits
end
Portrait.rb
class Portrait < ActiveRecord::Base
has_many :portrait_tags
has_many :tags, through: :portrait_tags
accepts_nested_attributes_for :portrait_tags
end
Portrait_tag.rb
class PortraitTag < ActiveRecord::Base
belongs_to :portrait
belongs_to :tag
end
Edit.html.haml
%h1 Edit Portrait
= form_for [:admin, @portraits], :html => { :method => :put } do |f|
- if flash[:system].present?
- flash[:system].each do |e|
%div= e
- if flash[:notice].present?
%div= flash[:notice]
= f.fields_for :portrait_tags do |a|
= a.collection_select :tag_id, Tag.all, :id, :name, {}, {multiple: true}
= f.submit "Save changes", class: "btn btn-primary"
PortraitController
class Admin::PortraitsController < ApplicationController
def edit
@portraits = Portrait.where(artist_id: 33, id: params[:id]).take
@portraits.portrait_tags.build
end
def update
@portrait = Portrait.where(artist_id: 33, id: params[:id]).take
if @portrait.update(portrait_params)
p portrait_params
else
flash[:system] = @portrait.errors.full_messages
p @portrait.errors.full_messages
render :edit
end
end
private
def portrait_params
# Permit our attributes
params.require(:portrait).permit(:id, portrait_tags_attributes: [:id, :tag_id => [] ])
end
end
portrait_tags表
+----+-------------+--------+
| id | portrait_id | tag_id |
+----+-------------+--------+
肖像表
+----+-----------+--------------+
| id | artist_id | artist_image |
+----+-----------+--------------+
标签表
+----+-----------+--------------------+
| id | name | portrait_tag_id |
+----+-----------+--------------------+
答案 0 :(得分:2)
<%= collection_select(:portrait_tag, :tag_ids,
Tag.all(:order=>"name ASC"),
:id, :name, {:selected => @portraits.tag_ids, :include_blank => true}, {:multiple => true}) %>
希望这对你有用。