如何在Ruby on Rails中使用Ajax更新两个参数?

时间:2013-05-25 12:39:32

标签: ruby-on-rails ruby ruby-on-rails-3 jquery ruby-on-rails-3.2

我正在尝试使用Ajax更新此辅助函数:

def radio_buttons_collection(types, invoice_type)
  types_html = types.map do |type|
    content_tag :span, :class => "radio_option" do
      radio_button_tag("project[invoice_type]", type, type == invoice_type) + type
    end
  end
  safe_join(types_html)
end

但是,我无法在那里获得这两个参数。

# get_invoice_types.js.erb:

$('#project_invoice_type').html("<%= escape_javascript(radio_buttons_collection(@types, @invoice_type)) %>");

# projects_controller.rb:

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

  project = Project.find(params[:id])
  @invoice_type = project.invoice_type
end

# application.js:

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

有人可以帮忙吗?

现在,只有@types参数才能正常传递。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

帮助Anezio Campos:

$("#project_person_id").change(function() {

    var person_id = $(this).val();
    var project_id = $("#project_id").val();
    $.ajax({
        url: '/projects/get_invoice_types',
        data: {person_id: person_id, id: project_id},
        dataType: 'script'
    })
});

尝试一下,如果有效的话。

答案 1 :(得分:1)

projects#get_invoice_types上,您正试图通过以下方式获取项目:

project = Project.find(params[:id])

但是你没有在你的ajax调用中传递id,你只是传递了person_id

你还应该在你的ajax调用中传递id param

添加一个id为project_id的hidden_​​field以及project.id

的值

然后

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