简体   繁体   中英

url_for does not work with custom route

I have a custom route that looks like:

match 'firsttime' => 'registrations#new', :via => :get, \
    :defaults => {:promotion_path => :firsttime}

The goal with the above route is to be able to have a url like http://www.mysite.com/firsttime which maps to the "new" method for the registrations controller, with the promotion for that registration being the "firsttime" promotion.

In one of my models, I have a shortcut method to try and generate this url:

class Registration < ActiveRecord::Base
  include ActionView::Helpers
  include ActionDispatch::Routing
  include Rails.application.routes.url_helpers

  belongs_to :promotion

  def get_share_link()
    promotion_path = promotion.url_path

    url_to_share = url_for :controller => 'registrations', :action => 'new', :promotion_path => promotion_path
  end
end

Calling the method get_share_links() fails with the error:

No route matches {:controller=>"registrations", :action=>"new", :promotion_path=>"firsttime"}

What am I doing wrong, or am I even using the right method for this?

routes are used in the Controller. Stick this as a before filter in your controller instead.

Edit #1

Is this devise or another gem for authentication?

EDIT #2

Can you get to http://www.mysite.com/registrations/new?promotion=firsttime presuming it's localhost for now of course, since you are in dev mode.

Question #1

What do you mean by "In one of my models, I have a shortcut method to try and generate this url:" what are you generating this for and where is it used? mailings? It seems your route works, it's just not being made when you want it to, and it's unclear where you want it to be used.

Answer

does it work with only_path: false supplied as an option?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM