2012-06-19 43 views
2

我正在使用rails 3.2。如何將模型的值設置爲f.label

我有許多到許多類型的模型。 有沒有辦法將模型的「值」設置爲field_for.label?

這是我想要做的。

客戶端模型

class Client < ActiveRecord::Base 
    attr_accessible :name, :renewal_month1, :renewal_month10, :renewal_month11, :renewal_month12, :renewal_month2, :renewal_month3, :renewal_month4, :renewal_month5, :renewal_month6, :renewal_month7, :renewal_month8, :renewal_month9, :sales_person_id, :usable, :user_id, :licenses_attributes 

    has_many :licenses, :dependent => :destroy 
    has_many :systems, :through => :licenses 
    accepts_nested_attributes_for :licenses 

end 

許可模式

class License < ActiveRecord::Base 
    attr_accessible :amount, :client_id, :system_id 

    belongs_to :client 
    belongs_to :system 
    def system_name 
    self.system.name 
    end 

end 

系統模型

class System < ActiveRecord::Base 
    attr_accessible :name, :sort 

    has_many :clients 

    has_many :licenses 
    has_many :clients, :through => :licenses 

end 

在客戶機控制器我建許可的對象爲所有系統。

def new 
    @client = Client.new 
    @title = "New Client" 

    System.all.each do |system| 
    @client.licenses.build(:system_id => system.id) 
    end 

    respond_to do |format| 
    format.html # new.html.erb 
    format.json { render json: @client } 
    end 
end 

在_form.html.erb我用fieds_for許可證

<%= f.fields_for :licenses do |ff| %> 
<tr> 
    <td><%= ff.label :system_id %></td> 
    </td> 
    <td> <%= ff.number_field :amount %> 
    <%= ff.hidden_field :system_id %> 
    <%= ff.hidden_field :system_name %> 
    </td> 
</tr> 
<% end %> 

結果我得到的是這種

<tr> 
    <td><label for="client_licenses_attributes_0_system_id">System</label></td> 
    </td> 
    <td> <input id="client_licenses_attributes_0_amount" name="client[licenses_attributes][0][amount]" type="number" value="10" /> 
    <input id="client_licenses_attributes_0_system_id" name="client[licenses_attributes][0][system_id]" type="hidden" value="1" /> 
    <input id="client_licenses_attributes_0_system_name" name="client[licenses_attributes][0][system_name]" type="hidden" value="SYSTEMNAME" /> 
    </td> 
</tr> 

我希望標籤這個樣子。

<td><label for="client_licenses_attributes_0_system_id">SYSTEMNAME</label></td> 

SYSTEMNAME是模型SYSTEM的值。 我在定義爲system_name的LICENSE模型中有一個虛擬屬性。 我能夠在隱藏字段中獲得SYSTEMNAME,所以我認爲模型和控制器都很好。 我只是無法找到如何設置模型的值來標籤。

回答

3

你爲什麼不能使用以下?

<%= ff.label :system_name %> 

我認爲,未來的代碼應該工作以及

<%= ff.label :amount, ff.object.system_name %> 

我不能對此進行測試,但我希望它會產生

<label for="client_licenses_attributes_0_amount">SYSTEMNAME</label> 

注意,它創建一個標籤對於金額字段,以便當用戶點擊它時,金額字段將被集中。

+0

感謝這工作得很好! '<%= ff.label:amount,ff.object.system_name%>' –

0

你有沒有嘗試添加系統名稱的標籤

<%= f.fields_for :licenses do |ff| %> 
<tr> 
    <td><%= ff.label :system_id, :system_name %></td> 

    <td> <%= ff.number_field :amount %> 
    <%= ff.hidden_field :system_id %> 
    <%= ff.hidden_field :system_name %> 
    </td> 
</tr> 
<% end %> 
+0

謝謝,但沒有很好地工作。 –

相關問題