2011-09-29 47 views
2

我正在Heroku上开发Rails 3应用程序,这里是这种情况:如何使一个Rails 3路由与2个控制器一起工作取决于数据库数据?

有两种模式:用户和应用程序。两者都具有 “蛞蝓”,并且可以通过相同的URL来访问:

/蛞蝓

实施例:

/为myuser> '用户#节目' /MYAPP => '应用#节目'

处理此问题的最佳做法是什么?我应该实施什么清洁解决方案?

您可以在AngelList上看到相同的逻辑。例如,我的个人资料是http://angel.co/martynasjocius,我的应用程序可以在http://angel.co/metricious找到。

谢谢!

回答

2

我会考虑引入第三个模型,我把它叫做Lookup作为例子,但是你可能想要找一个更好的名字。我还会假设你的用户和应用程序模型也定义了一个名称字段。

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 

我希望这个理念帮助,对不起,如果它没有用:)

0

试试这个(代action为自己的行为,像showedit等):

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 

独立的东西按照您认为合适的方式放入模块中。你可以让每个类的对象都有自己的操作。

相关问题