简体   繁体   English

从Rails模型访问数据库

[英]Accessing a Database from a Rails model

I'm writing a Rails application and I created a Grocery model that references a database table of grocery items. 我正在编写一个Rails应用程序,并且创建了一个杂货店模型,该模型引用了杂货项目的数据库表。 The Grocery table has just one column named "item". 杂货店表只有一列名为“ item”。

The Grocery model has a LIST constant that contains a bunch of "item"s. 杂货店模型的LIST常量包含一堆“项目”。 I seed the database with these items initially with the seeds.rb file. 我最初使用seeds.rb文件为这些项目添加数据库种子。 I also created a rake task to add/remove groceries from the database. 我还创建了一个rake任务,用于从数据库中添加/删除杂货。 The database is successfully populated. 数据库已成功填充。

The problem: I want to check the Grocery table within the Grocery model and other models to see whether or not a certain item is in the database. 问题:我想检查Grocery模型和其他模型中的Grocery表,以查看数据库中是否存在某个项目。 Every time I do a pry and access the Grocery table from within the Grocery model, I can't see any db items. 每次我进行撬动并从Grocery模型中访问Grocery表时,都看不到任何数据库项目。 (However, I can see the db items when I do a Grocery.all from the console and in rake tasks.) (但是,当我从控制台和rake任务中执行Grocery.all时,可以看到数据库项目。)

I've added attr_accessor :item to the Grocery model. 我已经将attr_accessor:item添加到了Grocery模型中。 This still does not work. 这仍然行不通。 What am I missing? 我想念什么?

If you have not added any default scope to the Grocery model, you should be able to fetch all the groceries inside Grocery or other models by using Grocery.all . 如果尚未向Grocery模型添加任何默认范围,则应该能够使用Grocery.all获取Grocery或其他模型中的所有杂货。 If you want to find if a certain grocery item exists in the grocery table, you can use Grocery.exists?(grocery_item_id) . 如果要查找食品杂货表中是否存在某种食品杂货,则可以使用Grocery.exists?(grocery_item_id) I hope it helps, if it doesn't, would recommend you to paste your model code here in the question. 希望对您有所帮助,如果没有帮助,建议您将模型代码粘贴到问题中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM