Event
确实已保存,但"artists":[]
为空,即使我选择了新表单中的多位艺术家。
新表格的相关部分如下所示:
<%= f.fields_for :event_artists do |fea| %>
<%= fea.collection_select :artist_id, Artist.all, "id", "name", {include_blank: true}, {multiple: true} %>
<% end %>
日志:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"OEh0j/cp35s/FABhsETxeQKnqZCKXrbZMpeeEE6P+KSM3QVF94zIluB1rqAD65ci5CP+R6tQS8V1f3SXIQ6Vtw==", "event"=>{"name"=>"", "date(1i)"=>"2016", "date(2i)"=>"7", "date(3i)"=>"22", "date(4i)"=>"01", "date(5i)"=>"55", "description"=>"", "venue_id"=>"1", "event_artists_attributes"=>{"0"=>{"artist_id"=>["", "1", "2"]}}}, "commit"=>"Create"}
Unpermitted parameter: artist_id
此控制器中允许使用此参数
def event_params
params.require(:event).permit(:id, :name, :date, :venue_id, :description, { event_artists_attributes: [:artist_id] })
end
event_artist模型如下所示:
class EventArtist < ApplicationRecord
belongs_to :event, optional: true
belongs_to :artist
end
事件模型:
class Event < ApplicationRecord
belongs_to :venue
has_many :event_artists
has_many :artists, through: :event_artists
accepts_nested_attributes_for :event_artists, reject_if: :all_blank, allow_destroy: true
end
事件控制器:
def create
@event = Event.new(event_params)
if @event.save
render json: @event, status: :created, location: @event
else
render json: @event.errors, status: :unprocessable_entity
end
end
def new
@event = Event.new
@artist = @event.event_artists.build
end
答案 0 :(得分:1)
你有一个不必要的哈希值event_artists_attributes
。相反,使用:
params.require(:event).permit(:id, :name, :date, :venue_id, :description, event_artists_attributes: [artist_id])
但是你有另一个问题。您尝试在仅EventArtist
belongs_to
Artist
has_many artists, through: :event_artists
Event
上设置多个艺术家ID。由于您的def event_params
params.require(:event).permit(:id, :name, :date,
:venue_id, :description, artist_ids: [])
end
模型上有<%= fields_for…
,因此您可以更改以下内容:
控制器:
<%= f.collection_select :artist_ids, Artist.all, "id", "name",
{include_blank: true}, {multiple: true} %>
在表单中,删除{{1}}块并将其替换为:
{{1}}
答案 1 :(得分:0)
试试这个:
params.require(:event).permit(:id, :name, :date, :venue_id, :description, { event_artists_attributes: [artist_id: []] })