Rails3 taskでDBのデータを参照できないエラーが発生する

このQ&Aのポイント
  • 自作したrakeファイルでDBのデータを参照・更新したいが、実行するとエラーになる。
  • rakeのコマンドではDBのモデルクラスを参照できない。
  • rails consoleでは正常に処理できるが、rakeのコマンドではDBの参照ができないようだ。
回答を見る
  • ベストアンサー

Rails3 taskでDBのデータを参照したい

自作したrakeファイルでDBのデータを追加・更新するような処理をしたいのですが、 うまく参照できずに実行してもエラーになります。 以下のようなソースです。 ---------------------------------------------------- namespace :glaph do desc "xxxxx" task :タスク名 do   --中略-- def login_at Time.current.strftime("%Y%m%d") end def get_user User.where(xxx: 1, login_at: login_at).first end def new_user user = User.new( is_period: 1, login_at: login_at ) user.save end def main new_user unless get_user end main end end ---------------------------------------------------- エラー内容: rake aborted! uninitialized constant User rails consoleではもちろん正常に処理できるのですが。。 rakeのコマンドではDB(modelクラス)を参照できないのでしょうか? お手数をお掛けしますが、宜しくお願いします。

  • Ruby
  • 回答数1
  • ありがとう数1

質問者が選んだベストアンサー

  • ベストアンサー
  • ki073
  • ベストアンサー率77% (491/634)
回答No.1

User classを定義していないからです。 中略のところが大事なのですが。 http://oshiete1.nifty.com/qa7409116.html のNo.1に実際に動くプログラムを載せておりますので参考に。 # table作成 の前までで何かが欠けているはずです。

taki11_ssw
質問者

お礼

回答ありがとうございます! 参考にさせて頂きます!

関連するQ&A

  • ruby on railsのmigrateでカラム名の変更ができません

    ruby on railsにて migrateでDBのカラム名を変更したいのですが、 エラーになってしまいます。 -エラーコード---------------------- rake aborted! uninitialized constant CreateArticles ----------------------------------- ★「datetime」カラム⇒「updated_at」カラムにしたい class RenameColumnArticles < ActiveRecord::Migration def self.up rename_column(:articles, :datetime, :updated_at) end def self.down rename_column(:articles, :updated_at, :datetime) end end よろしくお願いします。

  • Rails3でのルーティングの書き方

    Ruby1.9.3とRails3.2.9の環境でのルーティングではまってしまっているので、御経験のある方、御教示ください。現在、 config/routes.rbに Sample::Application.routes.draw do resources :users resources :tasks match '/users/login' match '/users/logout' match ':controller(/:action(/:id))' match ':controller(/:action(/:id))(.:format)' end を記述して、WEBrickを起動して、 http://localhost:3000/users/login/ を実行すると、このアドレスには移動するのですが、 NoMethodError in Users#show Showing C:/user/Ruby193/rails/sample/app/views/users/show.html.erb where line #5 raised: のエラーが出ます。 WEBrickの表示を見てみると、 Started GET "/users/login/" for 127.0.0.1 at 2013-01-22 22:56:06 +0900 Processing by UsersController#show as HTML Parameters: {"id"=>"login"} Rendered users/show.html.erb within layouts/users (2.0ms) Completed 500 Internal Server Error in 5ms となっていて、/users/login/をGETしているのですが、アクションでshowが呼び出されて、そのIDとして loginが渡っているように見えます。 現在、users\controller.rbのshowの関数の定義は全てコメントアウトしています。usersコントローラの def login関数の定義と、app/views/users/login.html.erbも置いているのですが、それらが表示されない状態で原因が分かりかねています。 上記のルーティングの書き方に何か問題があるのでしょうか?

    • ベストアンサー
    • Ruby
  • ユーザー定義関数の意味

    下記のユーザー定義関数の意味を自分なりに解釈しました。 下記の意味で合っていますか? // $dbと$user_idを受け取ったget_user関数は、$dbと$sqlを受け取ったユーザーの情報を取り出す function get_user($db, $user_id){ // データベースに接続してusersテーブルからuser_idが$user_idに一致するuser_id、name、password、typeを1行だけ表示する $sql = " SELECT user_id, name, password, type FROM users WHERE user_id = {$user_id} LIMIT 1 "; return fetch_query($db, $sql); } // $dbを受け取ったget_login_user関数は、変数dbと変数login_user_idを受け取ったget_user関数を返す function get_login_user($db){ // 変数login_user_idをセッションのユーザーIDと定義する $login_user_id = get_session('user_id'); return get_user($db, $login_user_id); }

    • ベストアンサー
    • PHP
  • Rails テストスクリプトの実行時にエラー

    Ruby on Railsのテストスクリプトの実行しようとするとエラーが発生します。 ------------------------------------------------------------------------------------------------- C:\Users\user\rails\sample>ruby bin/rake test test/models/sample_test.rb rake aborted! ActiveRecord::PendingMigrationError: Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=test C:/Users/user/rails/sample/test/test_helper.rb:3:in `<top (required)>' C:/Users/user/rails/sample/test/models/sample_test.rb:1:in `require' C:/Users/user/rails/sample/test/models/sample_test.rb:1:in `<top (required)>' Tasks: TOP => test:models (See full trace by running task with --trace) ------------------------------------------------------------------------------------------------- どのようにすればテストスクリプトを実行できるか教えていただけますでしょうか。

  • Interactive Rubyについて質問です。

    継承を用いて、次のクラスを表し、出力したいのですが、出力の仕方が良く分かりません。 classの作成まで自分でやったのですが(合っているかは分かりません。間違っていたら教えていただけると幸いです。)、その後、どう出力すればいいのでしょうか。 この問題のの趣旨としては以下のような感じです。 )継承を用いて、次のクラスを表したい。 人を大きく分けてアジア人、アフリカ人、ヨーロッパ人に分けるとします。 人を親のクラスとし、アジア人、アフリカ人、ヨーロッパ人を子のクラスとします。 人(親クラス)の大陸をcontinentで表し、 アジア人、アフリカ人、ヨーロッパ人の特徴はこれにskincolorを加えたものとします。 人、アジア人、アフリカ人、ヨーロッパ人のクラスを作成します。 この時、これらの特徴にアクセスするためのメソッドも合わせて定義し、 これらも継承関係が維持されるようにします。 最後に結果を出力したいのですがそこが分かりません。 自分で作成したクラスは以下のようです。 irb(main):001:0> class People irb(main):002:1> def initialize(continent) irb(main):003:2> @conti=continent irb(main):004:2> end irb(main):005:1> def get_conti irb(main):006:2> @conti irb(main):007:2> end irb(main):008:1> end => nil irb(main):009:0> class Asian < People irb(main):010:1> def initialize() irb(main):011:2> super(asia) irb(main):012:2> @yellow=color irb(main):013:2> end irb(main):014:1> def get_conti irb(main):015:2> @conti irb(main):016:2> end irb(main):017:1> def get_color irb(main):018:2> @yellow irb(main):019:2> end irb(main):020:1> end => nil irb(main):021:0> class African < People irb(main):022:1> def initialize() irb(main):023:2> super(africa) irb(main):024:2> @black=color irb(main):025:2> end irb(main):026:1> def get_conti irb(main):027:2> @conti irb(main):028:2> end irb(main):029:1> def get_color irb(main):030:2> @black irb(main):031:2> end irb(main):032:1> end => nil irb(main):033:0> class European < People irb(main):034:1> def initialize() irb(main):035:2> super(europa) irb(main):036:2> @white=color irb(main):037:2> end irb(main):038:1> def get_conti irb(main):039:2> @conti irb(main):040:2> end irb(main):042:1> def get_color irb(main):043:2> @white irb(main):044:2> end irb(main):045:1> end => nil ご教授お願い致します。

    • ベストアンサー
    • Ruby
  • rails3初心者 年齢を表示する

    rails3を勉強中です。 お詳しい方、ご教授いただけたら嬉しいです。 実装したい内容 プルボンタンで年齢「20」が選ばれた場合、 その結果を出力する(非モデル) ==================== views:presons/index.html ==================== <%= form_tag :action => :age do %> <%= select("form","age", (1..100))%> <%= submit_tag "表示する"%> <% end %> ==================== presons_controller.rb ==================== def index @preson = Preson.new end def age @preson = params[:form][:age] redirect_to :action => 'index' end ==================== views:presons/index.htmlで選択された 「20」を表示したいのですが、 そのコードの書き方をご教授ください。 どうぞよろしくお願い致します。

    • ベストアンサー
    • Ruby
  • singletonメソッドへのアクセス

    インスタンスメソッドからsingletonメソッドへのアクセスが、思ったようにできません。 はじめは、次のように記述すれば動作すると思っていました。 (MyClass.get_hello_wordをインスタンスメソッドから呼び出し) class MyClass  def hello   puts self.get_hello_word # エラー発生源  end  def self.get_hello_word   'hello every one'  end end MyClass.new.hello # エラー しかし、実際には次のように記述しなければ動きませんでした。 class MyClass  def hello   puts self.class.get_hello_word # self.classのワンクッション  end  def self.get_hello_word   'hello every one'  end end MyClass.new.hello そもそも、 def self.get_hello_word と定義したんだから、参照する時も同様にできてもいいのではないかと思うんですけれど、何か認識が間違っているのでしょうか。 だとしたら、(勘で言いますと) class << MyClass  def get_hello_word   'hello every one'  end end の文法の考え方がからんでいるような気がするのですが・・ ちんぷんかんぷんです。 どうかこの辺りの知識を教えて頂けないでしょうか。 あと、self.class.get_hello_wordの記述方法よりも簡単な(そうすべき)書き方があれば教えて下さい。

    • ベストアンサー
    • Ruby
  • rails3初心者 金額から絞り込み検索

    rails3を勉強中です。 ご教授いただけば幸いです。 実装したい事: DBに登録してあるproductsの一覧から金額を指定して絞り込み検索をしたい 解決してない事: indexに検索結果が表示されません。 コードの書き方をご教授いただければ幸いです。 ==================== views: ==================== <%= form_tag ({:controller => :products, :action => :search_price }), {:method => :post} do %> 価格指定 <%= text_field_tag "price1" %> ~  <%= text_field_tag "price2" %> <%= submit_tag "検索"%> <% end %> ==================== products_controller.rb ==================== def search_price @products = Product.all @product = Product.new @products.each do |product| item = product.price >= params[:price1].to_i && product.price <= params[:price2].to_i if item @product = product end end render :action => 'index' end ==================== views/products/index.html ==================== <% @products.each do |product| %> <%= product.name %> <%= product.price %> <% end %>

    • ベストアンサー
    • Ruby
  • 演算子の再定義とインスタンス変数の参照と代入

    list9.1とlist 9.3をあわせた二次元の座標、xとyを持つ プログラムです class Point attr_reader :x, :y def initialize(x=0, y=0) @x, @y = x, y end def inspect # 表示用 "(#{x}, #{y})" end def +(other) # x、yのそれぞれを足す self.class.new(x + other.x, y + other.y) end def -(other) # x、yのそれぞれを引く self.class.new(x - other.x, y - other.y) end def [](index) case index when 0 x when 1 y else raise ArgumentError, "out of range `#{index}'" end end def []=(index, val) case index when 0 self.x = val when 1 self.y = val else raise ArgumentError, "out of range `#{index}'" end end end point = Point.new(3, 6) p point[0] #=> 3 p point[1] = 2 #=> 2 p point[1] #=> 2 p point[2] #=>エラー(ArgumentError) についてお尋ねしたいのですが、 def [](index)で演算子を再定義する際、値を参照する方法で def [](index)  case index  when 0   x   : と、していますが、xp.135のアクセサの説明など では@xと「@」が要りそうな感じがするのですが、この 場合は省いて大丈夫なんでしょうか? プログラムがローカル変数と間違って処理したりという ことは無いんでしょうか。 仮にないとすれば、ここのcase文にはインスタンス変数 と同じ名前のローカル変数などは定義できないのでしょうか? ご教授願います。

    • ベストアンサー
    • Ruby
  • PHPフレームワーク Ethna DB作成

    LLフレームワークBOOKS「Ethna×PHP」をやっています。 P161のデータベース作成のところで質問です。 行った手順は以下です。 プロジェクトディレクトリ(/home/ethna/projects/ethnatask)に dbs/taskディレクトリを作成 ↓ taskディレクトリとdbs ディレクトリに書き込み権限追加 ↓ 以下のスクリプトを入力し「make_db.php」と名前を付けてdbsディレクトリに配置。 ------------ <?php $queries[] = <<<EOD CREATE TABLE task ( id INTEGER PRIMARY KEY, user VARCHAR, name VARCHAR, rate INTEGER DEFAULT 0, comment VARCHAR, created_at INTEGER, updated_at INTEGER, deleted_at INTEGER DEFAULT 0, task_order INTEGER NOT NULL ); EOD; $db = sqlite_open('./task/ethnatask.db', 0666); foreach ($queries as $query) { print("Execute query at\n{$query}\n"); sqlite_query($db, $query); } ?> ------------- ↓ ここから質問です。 本には「Webブラウザからmake_db.phpを呼び出すと、taskディレクトリ内に「ethnatask.db」が作成される」と記載があります。 Webブラウザからmake_db.phpをどうやって呼び出すのですか? ドキュメントルートは /var/wwwです。 シンボリックリンクを張っているので、http://localhost/ethnatask でトップ画面の表示までは確認できています。 Webブラウザからmake_db.phpを呼び出すとはどうやるのでしょうか?

    • 締切済み
    • PHP