LoginSignup
2
1

More than 5 years have passed since last update.

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

Posted at

環境

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
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1