除了使用execute方法之外,还有其他方法可以在rails中编写此查询吗?
connection.execute("select value_1, value_2, value_3 from table1 join table2 on table2.table1_id = table1.id where table2.table3_id = table3_id_value")
除了使用execute方法之外,还有其他方法可以在rails中编写此查询吗?
connection.execute("select value_1, value_2, value_3 from table1 join table2 on table2.table1_id = table1.id where table2.table3_id = table3_id_value")
如果您遵循 Rails 的复数和大写名称约定,这会容易得多。
那么如果 table1 是真的foos并且 table2bars对应于 Active RecordFoo和Bar声明,你会想要
belongs_to :foo
在Bar记录中。这对应于一个外键foo_id。然后添加匹配
has_many :bars
在Foo记录中。这允许检索所有使用bars引用foo的记录foo.bars。有了这一切,查询将是
Foo.join(:bar).select(:value_1, :value_2, :value_3)
.where('bars.table3_id = ?, table3_id_value)
可以覆盖表和外键名称的默认约定。在Active Record 查询文档中查找正确的选项。