我在保存has_many :through协会的记录方面遇到了一些问题。我一定错过了一些重要的事情。
首先要做的是:
我有三个模特:
class Event < ApplicationRecord
has_many :events_timeslots
has_many :timeslots, through: :events_timeslots
end
class Timeslot < ApplicationRecord
has_many :events_timeslots
has_many :events, through: :events_timeslots
end
class EventsTimeslot < ApplicationRecord
belongs_to :event
belongs_to :timeslot
end据此,每个事件都有很多时隙,每个时隙都有很多事件。
在我看来,我想要一个多元化的选择:
<%= form_with(model: event, local: true) do |form| %>
...
<% fields_for :events_timeslots do |events_timeslots| %>
<%= events_timeslots.label :timeslots %>
<%= events_timeslots.select(:timeslots, @timeslots.collect {|t| [t.name, t.id]}, {}, {multiple: true}) %>
<% end %>
...
<% end %>这是在创建新事件时选择多个时隙的正确方法吗?时隙此时已经存在,但是当事件被保存时,它还应该在events_timeslots表中创建相关的记录。
我还允许强参数中的timeslots属性:
params.require(:event).permit(:date, timeslots: [])有没有一种神奇的Rails方法可以使用“脚手架”控制器操作来创建新事件以及EventsTimeslot模型中的相关记录?关于这个问题,我找到了对另一个问题的回答,但是我无法让它工作!
也许我错过了一件很愚蠢的小事,但不管怎样,还是谢谢你的帮助。
编辑
(混乱的) events_timeslots表( schema.rb )
create_table "events_timeslots", force: :cascade do |t|
t.bigint "events_id"
t.bigint "timeslots_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["events_id"], name: "index_events_timeslots_on_events_id"
t.index ["timeslots_id"], name: "index_events_timeslots_on_timeslots_id"
end发布于 2017-11-06 20:11:22
假设你的外键是标准的:event_id和timeslot_id..。
然后尝试在timeslots方法中用timeslot_ids交换permit:
params.require(:event).permit(:date, timeslot_ids: [])
然后,与其以嵌套的形式设置联接表的属性,不如更新@event上的@event
<%= form_with(model: event, local: true) do |form| %>
<%= form.select(:timeslot_ids, Timeslot.all.collect {|t| [t.name, t.id]}, {}, {multiple: true}) %>
<% end %>发布于 2017-11-06 23:29:35
fields_for用于在使用accepts_nested_attributes创建嵌套记录时使用。
当您只是将项关联起来时,它就不需要了:
<%= form_with(model: event, local: true) do |form| %>
<%= f.collection_select(:timeslot_ids, Timeslot.all, :id, :name, multiple: true) %>
<% end %>ActiveRecord为has_many关联创建一个_ids设置器方法,该方法接受一个ids数组。这与表单帮手携手并进。
若要白名单数组参数,需要将其作为关键字传递以允许:
params.require(:event).permit(:foo, :bar, timeslot_ids: [])使用[]允许任何标量值。
发布于 2017-11-06 17:15:20
我想你是在找“自动存盘”,看看这里,http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html
https://stackoverflow.com/questions/47141776
复制相似问题