0

I am have a xyz method in one controller. Now I have a url 'buy-m-get-n' which will call xyz action.

get "/buy-m-get-n" => "store#xyz"

Now I want to call the same action for different values of m and n. eg: 'buy-2-get-3', 'buy-4-get-5'. m ,n <= 10

I tried this in routes.rb,

[1..10].each do |x|
  [1..10].each do |y|
    get "/buy-#{x}-get-#{y}" => "store#xyz"
  end
end

But it gives me new url as,

/buy-1..10-get-1..10-free

2 Answers 2

2

The way you are doing is not standard way.

Why do you not try like this:-

get "/buy/:m/get/:n" => "store#xyz", as: :buy_get

in this way you can use this url for different value for m and n for example: -

buy_get_path(m: 1, n: 2) #this will generate url like - /buy/:1/get/:2
buy_get_path(m: 3, n: 4) #this will generate url like - /buy/:3/get/:4

as per your requirement: -

get 'buy-:m-get-:n', to: 'articles#buy_get', as: :buy_get

and you can use it as: -

buy_get_path(m: 1, n: 2) # this will generate url like: - buy-1-get-2
Sign up to request clarification or add additional context in comments.

6 Comments

It works but I want /buy-1-get-2-free instead of /buy/2/get/3/free
@shubhammishra hi you can do this also. i m modifying the answer. please check it.
@shubhammishra in routes get 'buy-:m-get-:n', to: 'articles#buy_get', as: :buy_get use this. and use in view layer buy_get_path(m: 1, n: 2)
Thank you @gabbar
@shubhammishra i would suggest you to do like this as this is more dynamic instead of hard-coded routes. tomorrow you may need more routes then you can go each time in routes do customise your loop for this routes. feel free to accept/upvote answer if it helped you.
|
1

If n will be always fixed to 1 to 10, remove the brackets. [1..10] is an array of Range, 1..10 is the Range.

1..10.each do |x|
  1..10.each do |y|
    get "/buy-#{x}-get-#{y}" => "store#xyz"
  end
end

Range documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.