gpt4 book ai didi

ruby-on-rails - Rails 3嵌套表格

转载 作者:行者123 更新时间:2023-12-04 03:17:15 25 4
gpt4 key购买 nike

我有一个人模型和一个地址模型:

class Person < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address
end


class Address < ActiveRecord::Base
belongs_to :person
end

在我的人员 Controller 中,我的新操作中包含 @person.build_address。我的表格构建正确。问题是,当我提交表单时,会创建一个人记录和一个地址记录,但是它们没有通过“人”表中的address_id列进行链接。

我在 Controller 中错过了一步吗?

谢谢!

新 Action
更新
def new
@person = Person.new
@person.build_address

respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @person }
end
end

表格代码
更新
<%= form_for(@person) do |f| %>
<% if @person.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@person.errors.count, "error") %> prohibited this person from being saved:</h2>

<ul>
<% @person.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>

<div class="field">
<%= f.label :first_name %><br />
<%= f.text_field :first_name %>
</div>
<div class="field">
<%= f.label :last_name %><br />
<%= f.text_field :last_name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :telephone %><br />
<%= f.text_field :telephone %>
</div>
<div class="field">
<%= f.label :mobile_phone %><br />
<%= f.text_field :mobile_phone %>
</div>
<div class="field">
<%= f.label :date_of_birth %><br />
<%= f.date_select :date_of_birth %>
</div>
<div class="field">
<%= f.label :gender %><br />
<%= f.select(:gender, Person::GENDER_TYPES) %>
</div>
<div class="field">
<%= f.label :notes %><br />
<%= f.text_area :notes %>
</div>
<div class="field">
<%= f.label :person_type %><br />
<%= f.select(:person_type, Person::PERSON_TYPES) %>
</div>

<%= f.fields_for :address do |address_fields| %>
<div class="field">
<%= address_fields.label :street_1 %><br />
<%= address_fields.text_field :street_1 %>
</div>
<div class="field">
<%= address_fields.label :street_2 %><br />
<%= address_fields.text_field :street_2 %>
</div>
<div class="field">
<%= address_fields.label :city %><br />
<%= address_fields.text_field :city %>
</div>
<div class="field">
<%= address_fields.label :state %><br />
<%= address_fields.select(:state, Address::STATES) %>
</div>
<div class="field">
<%= address_fields.label :zip_code %><br />
<%= address_fields.text_field :zip_code %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>

最佳答案

您需要在自己的accepts_nested_attributes_for :address模型上安装Person才能正常工作。然后,您可以在create操作中执行以下操作:

def create
@person = Person.new(params[:person])
...
end

然后,Rails将负责其余的工作。

更新:如果 address_id列在 people表中,则它应该是 belongs_to :address,而不是 has_one :address

关于ruby-on-rails - Rails 3嵌套表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5073698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com