如何更新与导轨形式多模型
问题描述:
我有以下两种模式如何更新与导轨形式多模型
class Office < ActiveRecord::Base
has_many :locations, :dependent => :destroy
end
class Location < ActiveRecord::Base
belongs_to :office
end
我有一个办事处模型new.html.erb
和下面的代码在OfficeController
def create
@office = Office.new(params[:deal])
if @office.save
redirect_to office_url, :notice => "Successfully created office."
else
render :action => 'new'
end
end
如何添加字段Location
模型new.html.erb
的Office
?
我希望能够在同一个表单中有位置的字段。
答
你将不得不使用嵌套属性来做到这一点。幸运的是,Rails使它变得非常简单。以下是如何做到这一点:
首先,表示要办,你给它定位领域以及通过加入这一行:
accepts_nested_attributes_for :location
。-
现在,在
new.html.erb
中,添加所需的字段。假设我们希望有城市和国家:<%= f.fields_for :location do |ff| %> <%= ff.label :city %> <%= ff.text_field :city %> <%= ff.label :state %> <%= ff.text_field :state %> <% end %>
这就是它!