[英]Rails - Autocreate an associated model
我是Rails的新手,正在創建一個簡單的應用程序,該應用程序的客戶端帶有加法器。 在從堆棧溢出社區獲得一些建議和意見之后,我決定將地址另存為單獨的模型
我現在正在嘗試在我的應用程序中實現此功能,但是在從“新客戶端”表單中獲取要正確保存的地址時遇到了問題。 到目前為止,這是我的代碼:
class Address < ActiveRecord::Base
belongs_to :client
end
class Client < ActiveRecord::Base
has_one :address
before_create :build_address, unless: Proc.new { |client| client.address }
end
<%= form_for(@client) do |f| %>
<% if @client.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@client.errors.count, "error") %> prohibited this client from being saved:</h2>
<ul>
<% @client.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :phone_number %><br>
<%= f.text_field :phone_number %>
</div>
<%= f.fields_for :address do |a| %>
<div class="field">
<%= a.label :house_number %><br>
<%= a.number_field :house_number %>
</div>
<div class="field">
<%= a.label :house_name %><br>
<%= a.text_field :house_name %>
</div>
<div class="field">
<%= a.label :post_code %><br>
<%= a.text_field :post_code %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
這樣,將成功創建客戶端,但是將使用空字段創建地址記錄。 沒有錯誤。
非常感激任何的幫助。
謝謝
首先-很少有ActiveModel回調不會引起悲傷的情況。 通常,將邏輯放入模型中是一件好事-但要使回調僅在需要它們時才運行,而不是例如在無關的測試中運行,幾乎是不可能的。
在這種情況下,您只需要構建地址,以便在新操作中預先填充表單輸入。 沒有任何其他原因可以使您的所有Client實例始終具有空地址記錄,以備不時之需。
因此,我們可以這樣做:
class Client < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address
end
class ClientController < ApplicationController
def new
@client = Client.new
@client.build_address
end
def create
@client = Client.create(client_params)
# ...
end
def client_params
params.require(:client)
.permit(
:name, :phone_number,
address_attributes: [:house_number, :house_name]
)
end
end
您將需要accepts_nested_attributes_for
:
#app/models/client.rb
class Client < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address
before_create :build_address, unless: Proc.new { |client| client.address }
end
這將允許您執行以下操作:
#app/controllers/clients_controller.rb
class ClientsController < ApplicationController
def new
@client = Client.new
@client.build_address
end
end
這應該為您工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.