Help us understand the problem. What is going on with this article?

railsでparamsからパラメータを取得するとundefined methodが出る。

More than 3 years have passed since last update.

環境

Rails: 4.2.2
OS: OS X El Capitan(10.11.4)

原因と対処法

検索フォームから条件を取得して検索するということをやろうとした。
検索フォームのviewのtext_fieldでkeywordを指定しているので、Controllerのparams[:keyword]で値を取得しようとたら下記のようなエラーが出た。

undefined method `keyword' for #<Search:0x007f9e0959cf00>

ソースは以下のとおり。

SearchesController.rb
class SearchesController < ApplicationController
  def index
    item_name = params[:keyword]
  中略
end

search.rb
class Search
  include ActiveModel::Model
  attr_accessor :title, :author, :pubilisher, :image
end
new.html.erb
<% provide(:title, "本の検索") %>
<h1>本の検索</h1>

<%= form_for @search, url: searches_path, method: 'get', html: {class: 'form-horizontal'}  do |f| %>

  <div class="form-group">
    <div class="col-md-2">
      <%= f.label :keyword %>
    </div>
    <div class="col-md-6">
      <%= f.text_field :keyword, class: 'form-control' %>
    </div>
  </div>

  <div class="form-group">
    <div class="col-md-2">
      <%= f.submit "検索", class: "btn btn-primary" %>
    </div>
  </div>
<% end %>

どうやらModelにkeywordがなかっただけのようだ。
keywordをModelに追加したら正常に 動くようになった。

search.rb
class Search
  include ActiveModel::Model
  attr_accessor :title, :author, :pubilisher, :image, :keyword
end
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away