2010-02-03 19 views
9

我搜索並嘗試了很多,但我無法完成它,因爲我想...所以這是我的問題。使用領域從一個協會(has_many)與formtastic在rails中的模型

class Moving < ActiveRecord::Base 
    has_many :movingresources, :dependent => :destroy 
    has_many :resources, :through => :movingresources 
end 

class Movingresource < ActiveRecord::Base 
    belongs_to :moving 
    belongs_to :resource 
end 

class Resource < ActiveRecord::Base 
    has_many :movingresources 
    has_many :movings, :through => :movingresources 
end 

Movingresources包含其他領域,如quantity。我們正在研究'賬單'的觀點。由於formtastic簡化了整個關係的事情,只是寫作

<%= form.input :workers, :as => :check_boxes %> 

,我得到一個真正不錯的複選框列表。但到目前爲止我還沒有發現的是:我如何使用'移動資源'中的其他字段,在每個複選框的下方或下方,從該模型中選擇所需的字段?

我看到了不同的方法,主要是手動循環對象數組並創建合適的表單,使用:for在form.inputs部分,或不。但是這些解決方案都不是乾淨的(例如,爲編輯視圖工作,但不適用於新視圖,因爲所需的對象沒有構建或生成,並且生成它們導致混亂)。

我想知道你的解決方案!

回答

8

好吧,我錯過了accep_nested_attributes_for的革命,這解釋了爲什麼它不是真的有效。

這引起了我一個很大的一步,但我想我的地方仍然有一些併發症與我的關係錯綜複雜^ _^

class Moving < ActiveRecord::Base 
    has_many :movingworkers, :dependent => :destroy 
    has_many :workers, :through => :movingworkers 
    accepts_nested_attributes_for :movingworkers 
end 


<% form.inputs :for => :movingworkers do |movingworker| %> 
    <%= movingworker.inputs :worker, :quantity %> 
<% end %> 
+1

請注意,實際的底層模型可以通過formbuilder直接訪問,因此:'movingworker.object'。在action_view/helpers/form_helper.rb中看到1244行:'attr_accessor:object_name,:object,:options' – 2012-10-17 18:31:59

+0

你是對的。很多事情已經改變,我學到了很多新東西,這對我來說很明顯,但應該提及。 – pduersteler 2012-10-20 17:56:47

1

如果這些字段不存在於新視圖中,那麼您可以測試它是否是新的(new_record?)並呈現一組不同的字段(如果您包裝到一個部分中可以相當乾淨方法)。

+0

謝謝,你說得對。但是因爲我使用rails,所以我習慣了簡單,所以我要求其他解決方案來選擇我最喜歡的。我也認爲這可能會幫助其他人。 – pduersteler 2010-02-04 07:08:18

4

Formtastic的:label_method選項可能會有所幫助。例如。

<%= form.input :movingworkers, :label_method => :worker %> 

<%= form.input :movingworkers, :label_method => Proc.new { |x| "#{x.worker} #{x.quantity}" } %>