Page.find(permalink: 'home')
# => Page.find(permalink: 'home')
# => ArgumentError: Unknown key: permalink
Page.where(permalink: 'home')
# => [#<Page id: 1, permalink: "home", content: "foo", created_at: "2014-05-14 01:54:06", updated_at: "2014-05-14 01:54:06">]
路线
get ':permalink', to: 'page#show', as: :page
模型
class Page < ActiveRecord::Base
validates_uniqueness_of :permalink
end
控制器
class PageController < ApplicationController
def show
@page = Page.find(permalink: params[:permalink])
end
def new
@page = Page.new
end
def create
@page = Page.new page_params
if @page.valid?
redirect_to @page
else
render :new
end
end
def update
@page = page.find(params[:permalink])
if @page.update(page_params)
redirect_to @page
else
render :edit
end
end
def edit
@page = page.find params[:permalink]
end
private
def page_params
params.require(:page).permit(:permalink, :content)
end
end
我在这里做些什么吗?
答案 0 :(得分:2)
这不是find
方法的工作方式。看看the Rails Guide。您传递一个主键,该主键可能在数据库中,也可能不在数据库中,而不是哈希值。 where方法可以采用散列或字符串。
Page.find(1)
# => [#<Page id: 1, permalink: "home", content: "foo", created_at: "2014-05-14 01:54:06", updated_at: "2014-05-14 01:54:06">]
Page.where(permalink: "home", content: "foo")
# => [#<Page id: 1, permalink: "home", content: "foo", created_at: "2014-05-14 01:54:06", updated_at: "2014-05-14 01:54:06">]