こんにちは!
railsで検索機能を実装したいですが、コーディング過程で上記の問題にぶつかり先に進めなくなってしまいました。。。
ぜひ、お力添えをお願いします!!
参考記事
検索用のgem「ransack」を使ってみる(http://qiita.com/LuckOfWise/items/e020e896e71d47d0c6a4)
ほぼ、上記事と同様のフローです。
ただし、私はwindowsですので、vi Gemfileのコードは無視しています。
以下、記入コードです。
【プロジェクトを作成】
rails new ransack_study -T --skip-bundle
cd ransack_study
【localeとtimezoneを設定】
config/application.rb
require File.expand_path('../boot', FILE)
〜〜 ( 中略 ) 〜〜
module RansackStudy
class Application < Rails::Application
〜〜 ( 中略 ) 〜〜
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
config.time_zone = 'Tokyo'
config.active_record.default_timezone = :local
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de config.i18n.default_locale = :ja # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" 〜〜 ( 中略 ) 〜〜
end
end
【Gemfileに追記】
vi Gemfile→無視
source 'https://rubygems.org'
gem 'rails', '3.2.11'
Bundle edge Rails instead:
gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
gem 'rails-i18n' # この行を追加(ransackには関係ないけどdate_select用)
gem 'ransack' # この行を追加
〜〜( 以下 略 )〜〜
【bundle installを実行】
bundle install
【今回のサンプル用にscaffold】
ユーザーモデルと、ユーザーが紐づく掲示板モデルを作成します。
rails g scaffold user name:string
rails g scaffold topic title:string content:text user:references
【掲示板モデルでユーザーを登録するためにちょろっと修正】
app/models/topic.rb
class Topic < ActiveRecord::Base
belongs_to :user
attr_accessible :content, :title, :user_id #この行を修正
end
【ユーザーをselectタグで選択できるように】
app/views/_form.html.erb
<%= form_for(@topic) do |f| %>
〜〜 ( 中略 ) 〜〜
【一覧からcontentを削除し、created_atを追加、ユーザー名を表示するように変更】
app/views/index.html.erb
<h1>Listing topics</h1> <table> <tr> <th>Title</th> <th>User</th> <th>Created At</th><!--この行を修正--> <th></th> <th></th> <th></th> </tr><% @topics.each do |topic| %>
<tr> <td><%= topic.title %></td> <td><%= topic.user.name %></td><!--この行を修正--> <td><%= topic.created_at.strftime('%Y/%m/%d %H:%M') %></td><!--この行を修正--> <td><%= link_to 'Show', topic %></td> <td><%= link_to 'Edit', edit_topic_path(topic) %></td> <td><%= link_to 'Destroy', topic, method: :delete, data: { confirm: 'Are you sure?' } %></td> </tr> <% end %> </table> <br /><%= link_to 'New Topic', new_topic_path %>
【詳細でユーザー名を表示するように変更】
app/views/topic/show.html.erb
〜〜 ( 中略 ) 〜〜
【表示してみる】
http://localhost:3000/users → 成功!
http://localhost:3000/topics → 失敗…
エラー表示は
ブラウザ:NoMethodError in TopicsController#index
ターミナル:NoMethodError (undefined method attr_accessible' for #<Class:0x0000000ad80c48>): app/models/topic.rb:3:in
class:Topic'
app/models/topic.rb:1:in <top (required)>' app/controllers/topics_controller.rb:7:in
index'
という具合です。。。
ご意見お願い致します!!!
回答1件
あなたの回答
tips
プレビュー