RoR-在多对多联接表上创建记录 [英] RoR - create record on many-to-many join table
问题描述
我有以下型号:
Client.rb
has_many :establishments
accepts_nested_attributes_for :establishments
has_many :addressess, through: :establishments
accepts_nested_attributes_for :addresses
Establishment.rb
belongs_to :address
belongs_to :client
Address.rb
has_many :establishments
在Client
的show
视图上,我创建了<%= link_to "New Establishment", new_client_address_path(@client)%>
以便为客户端创建新的地址记录和新的Establishment.
On the show
view of the Client
I created a <%= link_to "New Establishment", new_client_address_path(@client)%>
in order to create a new Address record and a new Establishment to the client.
在AddressController
上,我有:
On the AddressController
I have:
def new
@client = Client.find(params[:client_id])
@address = @client.addresses.build
end
def create
@address = Address.new(address_params)
respond_to do |format|
if @address.save
format.html { redirect_to @address, notice: 'Estabelecimento criado com sucesso.' }
format.json { render action: 'show', status: :created, location: @address }
else
format.html { render action: 'new' }
format.json { render json: @address.errors, status: :unprocessable_entity }
end
end
end
这将创建新的地址,但不会创建新的场所.这样可以自动创建链接Client
和Address
的新场所吗?在您问之前,我真的需要这个Establishment
模型.
this will create the new Address but does not create the new Establishment. Can this automatically create the new Establishment that links the Client
and the Address
? Before you ask, I really need to have this Establishment
model.
推荐答案
此处:
在您的模型中:
Client.rb
has_many :establishments
accepts_nested_attributes_for :establishments
has_many :addresses, through: :establishments
accepts_nested_attributes_for :addresses
Establishment.rb
belongs_to :address
belongs_to :client
Address.rb
has_many :establishments
has_many :clients, through: :establishments
在您的控制器中:
class AddressController < ApplicationController
def new
@client = Client.find(params[:client_id])
@client.establishments.build.build_address
# if you have a column in establishment, for example: name
# you can do something like this to set establishment's name:
# @client.establishments.build(name: 'First connection').build_address
end
# create method doesn't need to be changed!!
end
您认为:
<%= form_for(@client) do |form| %>
<%= form.input :name %>
<%= form.fields_for(:establishments) do |establishment_form| %>
<% establishment = establishment_form.object.name.titleize %>
<%= establishment_form.input :name, as: :hidden %>
<%= establishment_form.fields_for(:address) do |address_form| %>
<%= address_form.input :address1, label: "#{establishment} address1" %>
<%= address_form.input :address2, label: "#{establishment} address2" %>
<% end %>
<% end %>
<%= form.submit "Submit" %>
<% end %>
你们都准备好了!
这篇关于RoR-在多对多联接表上创建记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!