开发者

How to make one Rails 3 route work with 2 controllers depending on database data?

I am developing a Rails 3 app on Heroku, and here is the situation:

There are two models: User and App. Both have "slugs" and can be accessed via the same url:

/slug

Example:

/myuser => 'users#show' /开发者_StackOverflow社区myapp => 'apps#show'

What is the best practice to handle this? What clean solution should I implement?

The same logic you can see on AngelList. For example, my personal profile is http://angel.co/martynasjocius, and my app can be found at http://angel.co/metricious.

Thank you!


I would think about introducing a third model, ill call it Lookup for the example, but you will probably want to find a better name. I will also assume your User and App models also define a name field.

class Lookup < ActiveRecord::Base
  belongs_to :owner, :polymorphic =>  true
  validates_uniqueness_of :name   
end

class User < Active::Record::Base
  has_a :lookup, :as => :owner, :validate => true
  before_create :create_lookup_record

  def create_lookup_record
    build_lookup(:name => name)
  end
end

class App < Active::Record::Base
  has_a :lookup, :as => :owner, :validate => true
  before_create :create_lookup_record

  def create_lookup_record
    build_lookup(:name => name)
  end
end

LookupsController < ApplicationController

  def show
    @lookup = Lookup.find_by_name(params[:id])
    render :action => "#{@lookup.owner.class.name.pluralize}/show"
  end

end

# routes.rb
resources :lookups

I hope this idea helps, sorry if its no use :)


Try this (substituting action for your actions, like show, edit, etc):

class SlugsController < ApplicationController
  def action
    @object = Slug.find_by_name(params[:slug]).object # or something
    self.send :"#{@object.class.to_s.downcase}_action"
  end

  protected
  def app_action
    # whatever
  end

  def user_action
    # something
  end
end

Separate stuff out into modules as you see fit. You can have objects of each class get their own actions.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜