Xaxum
Xaxum

Reputation: 3675

Rails 3 What is the proper way of passing parameters to controller in a manually constructed link?

I have four functions that I pass several parameters to over an ajax call. I build the url with javascript an example of one here:

    function submitMake(year,make){
    new Ajax.Request('update_model/'+year+'/'+make, { method: 'get'});
}

In my routes.rb I have four different entries set to receive the calls to send to the proper controller. Here is one:

    match 'car_infos/update_style/:year/:make/:model', :controller => 'car_infos', :action => 'update_style'

Everything works fine but I was wondering if this is a legit rails 3 way of doing it? If it is not, how should I modify my routes and what would the proper url look like?

Thanks for any input.

Upvotes: 4

Views: 226

Answers (2)

user324312
user324312

Reputation:

There is a more flexible solution for sharing urls between js and rails. With sprockets you can run your assets through ERB, then you can get at your url helpers that way.

For example, you could write out the url in a variable, with your paramaters hard coded to something you can replace in JS. That way you can change your urls without having to worry (as much) about changing your urls in your app.

Eg your.js.erb:

<% class << self; include Rails.application.routes.url_helpers; end %>
var urls  = {};
urls.make = <%= url_for(:only_path => true, 
                      :controller => :car_infos, :action => :update_style,
                      :make => '%make', :year => '%year', :model => '%model').to_json %>;
// urls.make will be: 'car_infos/update_style/%year/%make/%model'

function submitMake(year, make, model) {
    var path = urls.make.replace('%year', year).replace('%make', make).replace('%model', model);
    new Ajax.Request(path, {method: 'get'});
}

Upvotes: 1

apneadiving
apneadiving

Reputation: 115531

It's fine.

When working at the boundaries with js and ruby, there is not much syntax sugar available.

Upvotes: 4

Related Questions