Question

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?

Était-ce utile?

La solution

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">]
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top