16

私はレールなしでアクティブレコードを使用しようとしていますが、has_many が適切に機能していないようです。レールなしでアクティブレコードを使用したことはありません。単一のテーブルからクエリを実行できますが、関係が機能していないようです。誰かが一目見て、何か足りないかどうかを確認できますか。ここにスタブがあります

#!/usr/bin/ruby

require 'rubygems'
gem 'activerecord'

require 'sqlite3'
require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter => 'sqlite3',
  :database => 'test.db'
)

class User < ActiveRecord::Base
  has_many :problems
end

class Problem < ActiveRecord::Base
  belongs_to :users
end

def show_single_item
  pr = Problem.find(:first)
  puts "showing first problem from the db below", pr.desc
end

def show_all_items
  pr = Problem.find(:all)
  puts "showing all problems from the db below"

  pr.each do |a|
    puts a.desc
  end
end

def check_has_many
  user = User.find(:first)
  puts user.problem.desc
end

# run some methods 
show_single_item  # works
show_all_items    # works
check_has_many    # not working


------

here is the schema of users and problems from the database

sqlite> .schema users
CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "first_name"      varchar(255), "last_name" varchar(255));

sqlite> .schema problems
CREATE TABLE "problems" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "user_id"  integer, "desc" varchar(255));

and some selects to show some data from the tables

sqlite> select * from users;
2|mike|smit
3|mike|wilson

sqlite> select * from problems;
1||first problem
2||it went
3||this is a new problem
4||some more junk data

ここにエラーがあります

ruby-1.8.7-p352/gems/activemodel-3.2.3/lib/active_model/attribute_methods.rb:407:in `method_missing': \
undefined method `problem' for #<User id: 2, first_name: "mike", last_name: "smit"> (NoMethodError)
        from /home/wileybd/.rvm/gems/ruby-1.8.7-p352/gems/activerecord-3.2.3/lib/active_record/attribute_methods.rb:148:in `method_missing'
        from ./main.rb:38:in `check_has_many'
        from ./main.rb:44

任意の助けをいただければ幸いです。

4

2 に答える 2

6

私はあなたが何をしようとしているのか知っていると思います。私が間違っていなければ、特定のユーザーのすべての問題の desc 値を表示する必要があります。

必要なことを達成する簡単な方法は、最後の 2 つの方法を組み合わせることです。

user = User.first
user.problems.each do |pr|
  puts pr.desc
end

コードで発生している問題は、「ユーザーが抱えている各問題の説明を表示する」と言うのではなく、「ユーザーの問題の説明を表示する (単数形であることに注意してください)」のようなことを意味的に言っていることです。可能なものは次のようになります。

puts user.problems.descs  # This will not work

しかし、それはそれが機能する方法ではありません。ただし、使用できる新しい方法があります。

puts user.problems.pluck(:desc)

そのメソッドは、ユーザーの各問題の dess 値の配列を生成します。おそらく出力をいじって、好きなように印刷することができます。

于 2012-06-20T02:31:34.893 に答える
2

あなたが提供したスタックトレースは、エラーが何であるかを正確に示しています。それは check_has_many メソッドにあります:

def check_has_many
  user = User.find(:first)
  puts user.problem.desc # <==== should be user.problems
end

ユーザーには多くの問題があるため、複数形にする必要があります。

def check_has_many
  user = User.find(:first)
  puts user.problems.first.desc # <==== do this instead
end

また、Problem モデルでの belongs_to :users 関係は特異でなければなりません。

class Problem < ActiveRecord::Base
  belongs_to :user # <=== singular, not :users
end
于 2012-06-20T01:49:49.613 に答える