加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何使用无轨的活动记录

发布时间:2020-12-16 20:06:27 所属栏目:百科 来源:网络整理
导读:乡亲 我试图使用没有轨道的活动记录,似乎无法使has_many正常工作.我从来没有试过使用没有轨道的活动记录.我可以从单个表查询,但关系看起来似乎不起作用.任何人都可以快速浏览一下,看看是否有任何错误.这是存根 #!/usr/bin/rubyrequire 'rubygems'gem 'active
乡亲
我试图使用没有轨道的活动记录,似乎无法使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

任何帮助将不胜感激.

解决方法

我想我知道你想做什么如果我没有错误,你想要显示给定用户的每个问题的desc值.

完成所需要的一种简单的方式是最后两种方法的组合:

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

你在代码中遇到的问题是语义上你在说“显示用户的问题的描述(注意它是单数)”,而不是说“显示用户拥有的每个问题的描述”,如果它是可能应该是这样的:

puts user.problems.descs  # This will not work

但这不是它的工作方式.但是,您可以使用new method:

puts user.problems.pluck(:desc)

该方法将为用户生成每个问题的desc值的数组.你可以玩输出,以你喜欢的方式打印出来.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读