Ich sah verwandte Beiträge, konnte aber nicht meinen Code arbeiten. Ich habe Geräte und Projektmodelle, die durch projects_devices
Tabelle verbunden sind. Meine Modelle wie folgt aussehen:Speichern verknüpfte viele zu viele Relation in Rails
class Device < ActiveRecord::Base
has_many :projects, :through => :projects_devices
has_many :projects_devices
accepts_nested_attributes_for :projects_devices, allow_destroy: true
end
class Project < ActiveRecord::Base
has_many :devices, :through => :projects_devices
has_many :projects_devices
accepts_nested_attributes_for :projects_devices
end
class ProjectsDevice < ActiveRecord::Base
belongs_to :device
belongs_to :project
end
meine Gerätesteuerung:
def new
@device = Device.new
project_device = @device.projects_devices.build
@projects = Project.all
end
def create
@device = Device.create(device_params)
end
und meine device_param:
def device_params
params.require(:device).permit(:name, :projects_devices_attributes => [:id , project_id: []])
end
Meine Ansicht:
<%= f.label :Projects_devices %><br>
<%= f.fields_for :projects_devices do |proj| %>
<%= proj.select(:project_id, [], {}, {class: "form-control projects-devices", multiple: "multiple" }) do %>
<% if (@projects) %>
<% for @project in @projects %>
<%= content_tag(:option, @project.name, value: @project.id) %>
<% end %>
<% end %>
<% end %>
<% end %>
Ich habe eine viel zu viele Assoziationen zwischen zwei mo dels. Beim Erstellen und Bearbeiten von Geräten sollte ich alle verfügbaren Projekte auflisten können. Und wähle nur die benötigten aus. Wenn ich speichere, sollte die Tabelle projects_devices aktualisiert werden.
Ich habe mehrere Probleme hier:
Wenn ich ein neues Gerät zu speichern,
ein. Die
projects_devices
Tabelle hat nurdevice_id
, aber nichtproject_id
.project_id
ist nullb. Wenn es 2 Projekte gibt und ich nur eins auswähle, werden selbst dann zwei Assoziationsdatensätze mit nur
device_id
erstellt (wie oben erwähnt, fehltproject_id
). Es sollte nur eine Assoziation erstellen.Wenn ein neues Gerät bearbeitet wird,
ein. Projektliste, Liste aller Projekte ist leer.
b. Ich sehe 2 Auswahlfelder anstelle von einem für Projekte angezeigt werden (derzeit sind 2 Projekte vorhanden).
c. Das Aktualisieren des Geräts erfolgt nicht.
überprüfte ich die params:
"device"=>{"name"=>"ABC",
"projects_devices_attributes"=>{"0"=>{"project_id"=>["",
"298486374"]}}},
"commit"=>"Create Device"}
Meine Schienen-Protokoll zeigt, dass meine Anwendung nur device_id einfügt:
SQL (0.1ms) INSERT INTO `projects_devices` (`device_id`) VALUES (980190994)
Kann mir das Problem
Ich denke, die 'project_id' sein sollte' project_ids' (nur eine Vermutung) – Deep