如何将模型的值设置为f.label

时间:2012-06-19 14:27:44

标签: ruby-on-rails ruby-on-rails-3 fields-for

我正在使用rails 3.2。

我有很多种型号的模型。 有没有办法将模型的“值”设置为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的值。 我在LICENSE模型中有一个虚拟属性,定义为system_name。 我能够在hidden_​​field中获得SYSTEMNAME,所以我认为模型和控制器都很好。 我只是无法找到如何设置模型的值来标记。

2 个答案:

答案 0 :(得分:3)

为什么不能使用以下内容?

<%= ff.label :system_name %>

我认为下一个代码也可以正常运行

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

我无法测试,但我希望它会生成

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

注意,它会为金额字段创建一个标签,这样当用户点击它时,金额字段将被聚焦。

答案 1 :(得分:0)

您是否尝试过将system_name添加到标签

<%= 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 %>