所以我正在編輯一個編輯頁面,可以編輯動物和該動物的所有者。有一個連接表,其中包含什麼動物屬於什麼所有者。顯示器軌道連接表字段
更確切地說,假設你有:
<% form_for :animal, url: animal_path(@edit_animal), method: :patch do |edit| %>
... animal labels and fields to edit go here ...
<%= edit.fields_for :owners do |owner| %>
<%= owner.label :name, "Name" %>
<%= owner.text_field :name %>
<%end%>
<%=edit.submit 'Submit'%>
<%end%>
模型關聯:
AnimalOwner < ApplicationRecord
belongs_to :animal
belongs_to :owner
Owner < ApplicationRecord
has_many :animal_owners
has_many :animals, :through => :animal_owners
Animal < ApplicationRecord
has_many :animal_owners
has_many :owners, :through => :animal_owners
基本上,我不知道如果我做正確的形式連接表。我也希望能夠使用:value顯示當前保存在數據庫中的數據,但是我怎麼做到這一點呢?
<%= owner.text_field :name, :value => what_goes_here? %>
請問您可以正確添加模型及其關聯 –
通過一個簡單的連接表,就像您所描述的,您可以從三個不同的角度編輯表單。從動物控制器/視圖,所有者控制器/視圖和animal_owners控制器/視圖。如果登錄用戶是所有者,並且他們創建的任何動物都將是所有者,但是如果動物可以擁有多個所有者,那麼表單看起來會如何創建所有者 - 動物關係?編輯表單將是一個簡單的派生。 –