activerecord - 如何使用 ruby​​ activerecord 查询选择单列

标签 activerecord ruby-1.9.2

我在迁移目录下有两个类。

class1
  create_table :table1 do |t|
    t.integer :name
  end
end

class2
  create_table :table2 do |t|
    t.integer :table1_id
    t.integer :name
    t.text :value 
   end
end

我想使用条件 table2.table1_id = "1"和 table2.name = "A"从 table2 中仅获取值列

如何用 Ruby 编写这个? 我想得到文本值作为结果。 与sql查询相同

select value from table2 where table1_id = 1 and name = 'A';

最佳答案

您可以通过像这样应用查询来检索记录。

它会给你整行结果。你可以迭代这个数组并得到你的 期望值。

@array = Table2.where("table1_id = ? And name = ?",1,'A')

它会工作得很好。

或者

@array = Table2.find(:first,:conditions => "[table1_id = '1' And name = 'A']"

但是 ruby​​ 会警告您此代码已弃用,但它可以工作

但是第一个查询是最好的。

希望它对你有用!!!!

关于activerecord - 如何使用 ruby​​ activerecord 查询选择单列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9867071/

相关文章:

ruby - 为什么要求选择最新版本的 gem?

activerecord - 更改 Rails 记录中的 updated_at

ruby - quote_char 导致适合 ruby​​ CSV 导入

Ruby 1.9.2 语法错误

ruby-on-rails - 在 Ruby 1.9 中使用 instance_eval 进行常量查找

ruby-on-rails - ruby 1.9.2 中与 ruby​​ 1.8.7 不同的时间格式导致问题

database - Yii 记录未插入数据库

sql - 限制类别页面上产品列表中子类别的项目数量?

ruby-on-rails-3 - 将嵌套模型关联属性与包含匹配

ubuntu - RVM 配置问题 - "Missing RVM environment file"