Rails将局部变量从视图传递到js,控制器然后再返回到表单

时间:2014-01-31 06:30:09

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

我从下拉菜单中选择一个客户,根据选择它应该在下一个下拉列表中显示部门。

但是它给出了未定义的局部变量或方法f

NameError at /cus_departments
undefined local variable or method `f' for #<#<Class:0x000001078cbf88>:0x0000010782a138>

这是我的视图文件

new.html.haml

.page-content
  .page-header
    %h1 New agreement
  .row
    .col-xs-12
      = render :partial => 'form'
.actions
  = link_to 'Back', agreements_path

_form.html.haml

= form_for @agreement, :html => {:class => 'form-horizontal', :role => 'form'} do |f|
  .form-group
    %label.col-sm-3.control-label.no-padding-right.form-field-2
      = f.label :agreement_customer, 'Agreement customer'
  .col-sm-9
    #form-field-2.col-xs-10.col-sm-5.input.movies
      = f.select :agreement_customer, options_from_collection_for_select(Customer.all, :id, :customer_name), prompt: true
  .space-4
  .form-group
    %label.col-sm-3.control-label.no-padding-right.form-field-2
      = f.label :agreement_customer_dept, 'Customer department'
    .col-sm-9
      #form-field-2.col-xs-10.col-sm-5.input.characters
        %select{:class => 'form-control'}
          %option
  .space-4

agreement.js.coffee

$ ->
  $('.input.movies select').change ->
    url = "/cus_departments?customer_id=" + $(this).val() # get the selected value from the drop-down
    $('.input.characters select').load(url) # load the response from the url into the specified element(s)

agreements_controller.rb

def cus_departments

@customer = Customer.find_by_id(params[:customer_id])
@departments = @customer.departments

    render :partial => 'departments'
end

_departments.html.haml

= collection_select(:department, :customer_id, @departments, :id, :department, :prompt => "Select a department")

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您提供的内容有点令人困惑,但据我了解,我认为问题在于将检索到的值加载到选择框中。用户远程javascript或rjs是强大的,适合这种类型的要求。如果您愿意,我会发送一些代码示例。 :)