开发者

Dynamic select menu's in Rails?

I am trying to get dynamic select menu's working in my Rails application.

I have a model called kase, a model called person and a model called company.

When a user creates a new kase, they are presented with a select field to choose a Person and a select field to choose a Company.

I am trying to make it dynamic, so if they choose company a in the first select field then only employees of company a will be listed in the Person field.

The model associations are as follows:

class Kase < 开发者_运维知识库ActiveRecord::Base

  belongs_to :company # foreign key: company_id
  belongs_to :person # foreign key in join table
  belongs_to :surveyor,
             :class_name => "Company",
             :foreign_key => "appointedsurveyor_id"
  belongs_to :surveyorperson,
             :class_name => "Person",
             :foreign_key => "surveyorperson_id"

-------------------------------------------------  

class Company < ActiveRecord::Base
  has_many :kases
  has_many :people
  def to_s; companyname; end

-------------------------------------------------

class Person < ActiveRecord::Base
  has_many :kases # foreign key in join table
  belongs_to :company

UPDATED JAVASCRIPT

var people = new Array();
<% for person in @people -%>
  people.push(new Array(<%= person.company_id %>, '<%=h person.personname %>', <%= person.id %>));
<% end -%>

function personSelected() {
  alert('hello world');
  appointedsurveyor_id = $('kase_appointedsurveyor_id').getValue();
  options = $('kase_surveyorperson_id').options;
  options.length = 1;
  people.each(function(person) {
    if (person[0] == appointedsurveyor_id) {
      options[options.length] = new Option(person[0], person[1]);
      alert('hello world')
    }
  });
  if (options.length == 1) {
    $('kase_surveyorperson_id').hide();
  } else {
    $('kase_surveyorperson_id').show();
  }
}

document.observe('dom:loaded', function() {
  $('kase_appointedsurveyor_id').observe('change', personSelected);
});


var people = new Array();
<% for person in @people -%>
  people.push(new Array(<%= person.id %>, '<%=h person.login %>'));
<% end -%>

function personSelected() {
  alert('hello world');
  appointedsurveyor_id = $('company_appointedsurveyor_id').getValue();
  options = $('person_appointedsurveyorperson_id').options;
  options.length = 1;
  people.each(function(person) {
    if (person[0] == appointedsurveyor_id) {
      options[options.length] = new Option(person[0], person[1]);
    }
  });
  if (options.length == 1) {
    $('person_field').hide();
  } else {
    $('person_field').show();
  }
}

document.observe('dom:loaded', function() {
  //companySelected(); << remove this
  $('person_field').observe('change', personSelected);
});


Try observe_field. http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html#M002183

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜