为简洁起见编辑我的问题并更新我所做的事情:
如何为公司建模具有多个地址并将单个地址分配给联系人,并能够在创建或编辑联系人时分配它们?
我想使用嵌套属性在创建新联系人时添加地址。该地址作为其自己的模型存在,因为我可能希望选择从现有地址下拉而不是从头开始输入。
我似乎无法让它工作。我得到了一个未定义的方法“build”,用于 nil:NilClass 错误
这是我的联系人模型:
class Contact < ActiveRecord::Base
attr_accessible :first_name, :last_name, :title, :phone, :fax, :email, :company,
:date_entered, :campaign_id, :company_name, :address_id, :address_attributes
belongs_to :company
belongs_to :address
accepts_nested_attributes_for :address
end
这是我的地址模型:
class Address < ActiveRecord::Base
attr_accessible :street1, :street2, :city, :state, :zip
has_many :contacts
end
我想在创建新联系人时访问属于公司的其他联系人的所有地址。所以这是我代表公司的方式:
class Company < ActiveRecord::Base
attr_accessible :name, :phone, :addresses
has_many :contacts
has_many :addresses, :through => :contacts
end
以下是我尝试在 View for _form for Contact 中创建字段的方式,以便在有人创建新联系人时,他们将地址传递给地址模型并将该地址与联系人相关联:
<% f.fields_for :address, @contact.address do |builder| %>
<p>
<%= builder.label :street1, "Street 1" %> </br>
<%= builder.text_field :street1 %>
<p>
<% end %>
当我尝试编辑时,街道 1 的字段为空白。而且我不知道如何显示来自 show.html.erb 的值。
底部是我的错误控制台——似乎无法在地址表中创建值:
我的联系人控制器如下:
def new
@contact = Contact.new
@contact.address.build # Iundefined method `build' for nil:NilClass
@contact.date_entered = Date.today
@campaigns = Campaign.find(:all, :order => "name")
if params[:campaign_id].blank?
else
@campaign = Campaign.find(params[:campaign_id])
@contact.campaign_id = @campaign.id
end
if params[:company_id].blank?
else
@company = Company.find(params[:company_id])
@contact.company_name = @company.name
end
end
def create
@contact = Contact.new(params[:contact])
if @contact.save
flash[:notice] = "Successfully created contact."
redirect_to @contact
else
render :action => 'new'
end
end
def edit
@contact = Contact.find(params[:id])
@campaigns = Campaign.find(:all, :order => "name")
end
这是我的错误控制台的片段: 我正在发布属性,但它不是在地址表中创建...。
处理 ContactsController#create (for 127.0.0.1 at 2010-05-12 21:16:17)
[POST] 参数:{"commit"=>"Submit", "authenticity_token"=>"d8/gx0zy0Vgg6ghfcbAYL0YtGjYIUC2b1aG+dDKjuSs=", "contact"=>{"company_name"=>"Allyforce", "title"=>" ", "campaign_id"=>"2", "address_attributes"=>{"street1"=>"abc"}, "fax"=>"", "phone"=>"", "last_name"=>"" , "date_entered"=>"2010-05-12", "email"=>"", "first_name"=>"abc"}}
公司负载 (0.0ms)[0m [0mSELECT * FROM "companies" WHERE ("companies"."name" = 'Allyforce') LIMIT 1[0m
地址创建 (16.0ms)[0m
[0;1mINSERT INTO "addresses" ("city", "zip", "created_at", "street1", "updated_at", "street2", "state") VALUES(NULL, NULL , '2010-05-13 04:16:18', NULL, '2010-05-13 04:16:18', NULL, NULL)[0m联系人创建 (0.0ms)[0m
[0mINSERT INTO "contacts" ("company", "created_at", "title", "updated_at", "campaign_id", "address_id", "last_name", "phone", "fax" , "company_id", "date_entered", "first_name", "email") VALUES(NULL, '2010-05-13 04:16:18', '', '2010-05-13 04:16:18', 2, 2, '', '', '', 5, '2010-05-12', 'abc', '')[0m