我在聽Hypercritical時聽說過這個社區,我很高興能夠加入我的第一個問題。我正在開發我的第一個Rails應用程序,並且遇到了一個我似乎無法解決的問題。我一直在觀看Railscast,Lynda.com和谷歌搜索幾天,但我仍然無法理解如何創建一個可以更新我的has_many的表單:通過一次關聯。請允許我嘗試解釋我在做什麼。嵌套模型表單沒有提交所有內容
我的目標: 我所在的公司提供了許多「服務內容」,我希望能夠在一個頁面上創建一個新的服務產品,並將它創建一個與之關聯的聯繫人等信息。諸如「聯繫人」之類的附加信息將存在於他們自己的表格中,因爲它們可能需要被許多「服務提供」所引用。
問題: 當我提交了「服務產品」領域提交併輸入到數據庫的形式,但對於「商業開發」的字段不。很顯然,我希望將所有內容輸入到適當的表格中,並且要在連接表格中鏈接ID。我真的很感激你能提供的任何見解。
我到目前爲止:您在下面看到的是服務產品和業務開發人員。最終我會添加通訊錄,照片和文件,但我認爲我會開始簡單地工作。
型號:
class ServiceOffering < ActiveRecord::Base
attr_accessible :name, :description
has_many :business_developer_service_offerings
has_many :business_developers, :through => :business_developer_service_offerings
accepts_nested_attributes_for :business_developer_service_offerings
end
class BusinessDeveloper < ActiveRecord::Base
attr_accessible :first_name, :last_name
has_many :business_developer_service_offerings
has_many :service_offerings, :through => :business_developer_service_offerings
end
class BusinessDeveloperServiceOffering < ActiveRecord::Base
belongs_to :business_developer
belongs_to :service_offering
end
控制器:
def new
@service_offering = ServiceOffering.new
@service_offering.business_developers.build
end
def create
@service_offering = ServiceOffering.new(params[:service_offering])
if @service_offering.save
redirect_to(:action => 'list')
else
render('new')
end
end
查看:
<%= form_for((@service_offering), :url => {:action => 'create'}) do |f|%>
<p>
<%= f.label :name%>
<%= f.text_field :name %>
<%= f.label :description%>
<%= f.text_field :description %>
</p>
<%= f.fields_for :business_developer do |builder| %>
<p>
<%= builder.label :first_name%>
<%= builder.text_field :first_name %>
<%= builder.label :last_name%>
<%= builder.text_field :last_name %>
</p>
<%end%>
<%= f.submit "Submit" %>
<%end%>
我用更多的解釋更新了我的答案。你應該閱讀,這是肯定更清楚:http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for – Damien