简体   繁体   English

Rails 4 .joins()问题-不起作用

[英]Rails 4 .joins() issue — not working

Model for Plugin: 插件型号:

class Plugin < ActiveRecord::Base
    has_many :vulns
end

Model for Vuln: Vuln的模型:

class Vuln < ActiveRecord::Base
    belongs_to :plugin
end

Table for Plugin: 插件表:

create_table "plugins", force: true do |t|
    t.string "name"
end

Table for Vuln: Vuln表:

create_table "vulns", force: true do |t|
    t.string  "title"
    t.integer "plugin_id"
    t.string  "vulnerability_type"
    t.string  "fixed_in"
end

When I use rails console using rails c and enter Plugin.select("*").joins(:vulns) it only grabs data from the Plugin table 当我通过rails c使用rails console并输入Plugin.select("*").joins(:vulns)它仅从Plugin表中获取数据

#<ActiveRecord::Relation [#<Plugin id: 1, name: "xxx">, #<Plugin id: 2, name: "xxx">

This is the query: 这是查询:

SELECT * FROM `plugins` INNER JOIN `vulns` ON `vulns`.`plugin_id` = `plugins`.`id`

However, when I execute this query in mysql, it shows all content from vulns and plugins like its supposed to. 但是,当我在mysql中执行此查询时,它会显示来自vulns和插件的所有内容,就像它应该的那样。 For every plugin there is atleast one or more vuln in the database. 对于每个插件,数据库中至少有一个或多个漏洞。

So here's the question: How do I get it to fetch content from both tables (plugins and vulns) instead of just plugins? 所以这是一个问题:我如何才能从两个表(插件和vulns)中获取内容,而不仅仅是插件?

The vulns values are there, it's just not shown because you are using Plugin model to select, ie Plugin.select("*").joins(:vulns) . vulns值在那里,只是因为使用Plugin模型进行选择(即Plugin.select("*").joins(:vulns)

If you did the following, you will get the value: 如果执行以下操作,则将获得该值:

> plugin = Plugin.select("*").joins(:vulns)
> plugin.first.title 
=> "mytitle"

Because you are querying through Plugin model, you'll see Plugin object. 由于您正在通过Plugin模型进行查询,因此您将看到Plugin对象。

Another way to test this would be by doing the following: 另一种测试方法是执行以下操作:

> plugin = Plugin.select([:name, :title]).joins(:vulns)
=> #<ActiveRecord::Relation [#<Plugin id: 1, name: "xxxx">]>

# It won't show you title even though it's there
> plugin.title
=> "mytitle"

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

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