0

person我在 Rails 中有一个 ajax 函数,它根据在表单中选择的选项更新选项哈希:

# projects_controller.rb
def get_invoice_types
  person = Person.find(params[:person_id])  
  @types = person.address_types
end

# get_invoice_types.erb
$('#project_invoice_type').html("<%= escape_javascript(options_for_select(@types)) %>");

# application.js
$("#project_person_id").change(function() {
    $.ajax({
        url: '/projects/get_invoice_types',
        data: 'person_id=' + this.value,
        dataType: 'script'
    })
});

有没有一种简单的方法来生成一个列表radio_buttons而不是options_for_select

如果是这样,如何做到这一点?

谢谢你的帮助。

这是生成我最终得到的单选框的函数:

def collection_radio_buttons(types, f) # works!
  types_html = types.map do |type|
    content_tag :span, :class => "radio_option" do
      f.radio_button(:invoice_type, type) + localize_address_type(type)
    end
  end
  safe_join(types_html)
end

但是,我无法通过上面的 Ajax 函数对其进行更新。我猜这是由于f传递给函数的变量?

4

1 回答 1

1

label_tag使用和radio_button_tag循环元素编写你的开放助手。

更新

像这样的东西?

#Helper
  def radio_boxes(name, *items)
    content_tag :div do
      items.collect do |item|
        content_tag :label, item.first
        radio_button_tag(name, item.last) + label_tag("#{name}_#{item.last}", item.first)
      end.join("\n").html_safe
    end
  end

#View
<%= radio_boxes('countries', ['Lisbon', 1], ['Madrid', 2]) %>

#Output
<div>
  <input id="countries_1" name="countries" type="radio" value="1"><label for="countries_1">Lisbon</label>
  <input id="countries_2" name="countries" type="radio" value="2"><label for="countries_2">Madrid</label>
</div>
于 2013-03-04T20:34:15.630 回答