JackNova
JackNova

Reputation: 3931

Do you have to define controller helpers to get paths for new routes in rails?

I have a Customer model and I want his controller to repond to a find method

I added this in my routes.rb file:

match 'customers/find/:name' => 'mymodel#find' resources :customers

In my controller I have something like this:

def find
  @customers = Customer.fin_all_by_name(params[:name])
end

in my views, when I need to create a link for that resource I'm using this:

= link_to 'Find By Name', :controller => "customers", :action => "find", :name => @customer.name

now, I'm trying integration tests with cucumber and I have a problem: I have to create a step definition in my customer_step.rb file for customers having same name:

when /^customers having same name as "(.*)"/ url_encode('/customers/find/' + $1)

now that line doesn't work, it says undefined method `url_encode' I need to encode that string because if the name contains a space I get obvious errors.

I'm new to ruby and rails and I think I'm missing something here.

Am I following the right pattern to accomplish this search? Should I define an helper method in my controller to generate search urls? Is it correct that line I have in my _step.rb file?

I don't want urls to be like this: customers/find?name=test
but: customers/find/test

I just sorted it out, I slightly modified my match expression and added the :as parameter and this gave me the possibility to call find_path() helper method

match 'customers/find/:name' => 'customers#find', :as => :find

Is this correct?

Upvotes: 1

Views: 743

Answers (1)

ksol
ksol

Reputation: 12255

Using :as should indeed create a route helper for you. If you want to get a list of your matched routes, to which controller/action they route, and the name of the route helper, use rake routes in console.

Upvotes: 1

Related Questions