Kush
Kush

Reputation: 1522

Rails refuses to insert one field into the database

Basically I grab an the id of an element from a table and insert it into another.

vuln_id = ActiveRecord::Base.connection.execute("SELECT FROM BLAH WHERE ...")                   

pid = vuln_id.first

puts "=============================="
puts pid # this echos the ID
puts "=============================="

if pid.empty? 
    puts "pid is empty"
end

rd = Report.new(:plugin_id => pid, :report_id => report_id)
rd.save()

In Rails console, when I do

Report.dbaction(params)

It runs the model and here is the output

(0.3ms)  SELECT STATEMENT.....
==============================
186
==============================
(3.0ms)  BEGIN
SQL (0.3ms)  INSERT INTO `report_data` (`created_at`, `report_id`, `updated_at`) VALUES ('2013-07-10 22:03:59', 6, '2013-07-10 22:03:59')
(33.9ms)  COMMIT

It inserts report_id but it doesnt insert pid value into the database, even though it exists. Why is this?

Quick edit: plugin_id definitely exists in the table. I triple checked.

Here is what the rest of the model file looks like

class Report < ActiveRecord::Base

    belongs_to :site
    has_many :plugins

Upvotes: 0

Views: 173

Answers (1)

GSP
GSP

Reputation: 3789

You're getting the first result from the database query in line 1 but execute returns an array of arrays, I believe, that contains all the columns that you selected. You probably want: pid = vuln_id.first[0] or something like that (or pid = vuln_id[0][0] or pid = vuln_id.first.first).

You should also verify that the query returned anything at all so the entire line might be something like:

pid = vuln_id.first.first if vuln_id and vuln_id.count > 0

Upvotes: 1

Related Questions