2012-10-22 32 views
2

我试图按照http://railscasts.com/episodes/63-model-name-in-url实现这一看似URL:如何在URL中使用Rails资源的另一个属性?

/dog/<custom field of dog>

,而不是

/dog/1

其中 “1” 是狗表的内部主键。我想要的自定义字段恰好是Dog字段中的另一个整数。

我的代码:

dogs_controller.rb:

load_and_authorize_resource :except => [:index]  
def show 
     Rails.logger.info("Hello") 
     @dog = Dog.find_by_custom_field(params[:id]) 
    end 

dog.rb:

def to_param 
    custom_field 
end 

特别是,当我尝试加载/dogs/<custom_field>,但仍坚持使用该整数作为主键查找,而不是查看自定义字段。所以我得到一个Couldn't find Dog with id=<custom_field>。错误

有趣的是,当我尝试这样做时,记录器行也从未被打印。但是,当我删除load_and_authorize_resource(CanCan)行时,它就可以工作。这里发生了什么?

+2

你不只是需要重写'routes'设置?像'/ dog /:custom_field'一样。 – oldergod

回答

相关问题