簡體   English   中英

如何使用沒有rails的活動記錄

[英]How to use active record without rails

伙計我試圖使用沒有rails的活動記錄,似乎無法使has_many正常工作。 我從未嘗試使用沒有rails的活動記錄。 我可以從單個表中查詢,但這些關系似乎不起作用。 任何人都可以快速瀏覽一下,看看我是否遺漏了什么。 這是存根

#!/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

任何幫助,將不勝感激。

我想我知道你要做什么。 如果我沒有弄錯,你想顯示給定用戶的每個問題的desc值。

完成所需的簡單方法是結合最后兩種方法:

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)

該方法將為用戶生成每個問題的desc值的數組。 您可以使用輸出來按照自己喜歡的方式進行打印。

您提供的堆棧跟蹤確切地說明了錯誤。 它在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

此外,問題模型中的belongs_to:users關系應該是單數:

class Problem < ActiveRecord::Base
  belongs_to :user # <=== singular, not :users
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM