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">]
Route
get ':permalink', to: 'page#show', as: :page
Model
class Page < ActiveRecord::Base
validates_uniqueness_of :permalink
end
Controller
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
Am I doing something off here?
That's not how the find
method works. Take a look at the Rails Guide . You pass it a single primary key that may or may not be in the database, not a hash. The where method can take in a hash, or a string.
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">]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.