开发者

Updating one select box based on another (Ruby on Rails)

I'm new to Ruby on Rails, and need some help.

I'm working on a web application which can be used to keep track of cars. There are two models, one which represents makes (Saab, Honda, Toyota, etc) and another which represents models (Civic, Miata, PT Cruiser, etc). They have a "has_many" relationship:

script/generate scaffold make name:string

script/generate scaffold model name:string make_id:integer

I created a view with two select boxes (created using the select helper method), one for makes and开发者_开发技巧 one for models.

Here's what I'm having trouble figuring out how to do: I would like for the second select box to be populated only with the models which correspond to the make selected in the first. When the make changes in the first select box, so should the models in the second.

Thanks guys!


You'll want to create an ajax observer on the first make select box which updates the second select box. Something like the following:


  &lt%= select :make,:id, @makes %>
  &lt div id = "model_select"> &lt/div>
  &lt%= observe_field :make_id, :url => model_select_makes_path, #or whatever
            :with=>"make_id"%>

Then in your makes_controller:


def model_select
  make = Make.find(params[:make_id])
  @models = make.models
  respond_to do |format|
    format.js  
  end
end

and then either use an rjs partial like this or render :update in the controller:


 page.replace_html "model_select", :partial => "model_select"

And model_select.html.erb will have the html that renders the model selector using @models, something like:


  <%= select_tag :model, :id, @models %>


You just have to write a piece of JavaScript that submits the form via AJAX when the "make" selectbox changes and then, on the server-side, use an RJS view that will get your names into second selectbox.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜