开发者

How do I create a user-defined redirect in ruby on rails?

I have created a model called LandingPage, and the current route is something like:

www.domain.com/landing_pages/1

Or something like that. I will have several of these, so landing_page where id = 1...n.

However, when someone creates the landing page, I would like them to be able to define an attribute for the model, such as "superbowl" to redirect to landing_page/1, "nice" to landing_page/2, etc.

This would allow the user to define the landing page as:

subdomian.domain.com/superbowl 

which would resolve to

www.domain.com/landing_pages/1/

How do I do that? Each landing_page has an attribute 'shortname' which ties to its specific landing_page.

I am on Rails 2.3.8. My hunch is in the routes 开发者_JS百科to loop through the available shortnames, but not sure.

 8   def show
  9     
 10     @landing_page = LandingPage.where(:name => params[:name]).first
 11     redirect_to landing_page_path(@landing_page)
 12     
 13     #@landing_page = LandingPage.find(params[:id])
 14     @redcloth_landing_page = RedCloth.new(@landing_page.message).to_html
 15     form = "<div id='form'>" << @landing_page.form << "</div>"
 16     
 17     @redcloth_landing_page.gsub!("{Form}",form)
 18     
 19     render :layout => false
 20   end


Taking your comments into account, you need a RedirectsController, and in your routes.rb file, you would have:

map.connect '/:name', :controller => 'redirects', :action => 'show'

You need to make sure that this route comes after your resource routes. In your RedirectsController, the show method would be something like:

def show
  @landing_page = LandingPage.first(:conditions => {:name => params[:name]})
  redirect_to @landing_page
end

I'm not sure what you're trying to achieve at www.domain.com/landing_pages/1/, but using your code as an example, you should have the following in your LandingPagesController show action:

def show

  @landing_page = LandingPage.find(params[:id])
  @redcloth_landing_page = RedCloth.new(@landing_page.message).to_html
  form = "<div id='form'>" << @landing_page.form << "</div>"

  @redcloth_landing_page.gsub!("{Form}",form)

  render :layout => false
end

However, this solution is not as good as before because, unless I am missing it, I do not know that you can constrain a route to a subdomain in 2.3.8. Without constraining to subdomains, you would have to make sure your users did not use one of your controllers' names as a landing page word, adding complexity to your program.

There is a plugin, called subdomain-fu, which should allow you to restrict your routes to a subdomain. The project is located at https://github.com/mbleigh/subdomain-fu. I hope this helps, if not let me know.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜