添加到关系数据库rails



我有两个模型一个地址模型

class Address < ActiveRecord::Base
attr_accessible :address1, :address2, :country, :county, :customer_id, :town
belongs_to :customer    
end

和客户模型

class Customer < ActiveRecord::Base
attr_accessible :email, :firstname, :lastname, :password, :phone
has_one :address
end

我使用脚手架生成了CRUD功能。我希望能够做到的是,当我添加一个新客户时,我可以从文件上的地址中为客户选择一个地址,或者不选择地址。我可以使用这个查看客户和他们的地址。

def showaddress
@customer = Customer.find(params[:id])
@address = @customer.address
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @customer }
end
end

这是我用来创建新客户的当前控制器

def new
@customer = Customer.new
respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @customer }
end
end

基本上我想做的是当我创建一个新客户时,有一个地址下拉列表用户可以点击它将地址与客户关联

您可以初始化控制器中new方法中所有地址的变量,并在视图页中使用该变量来填充表单中的选择框。

def new
  @customer = Customer.new
  @addresses = Address.all
  #...
end

或直接在表单中填充地址,如下所示

select_tag 'address_id', options_for_select(Address.all.collect{ |a| [a.name, a.id] })

试试这个,

<%= select_tag :address_id, Customer.all.collect {|p| [ p.address_title, p.id ] } %>

最新更新