Reputation: 1718
I have a Pinterest Ruby crawler (not in Rails) where I write the data to a JSON file. I created a ActiveRecord for Pins. I also created a a method that loads the data from file to mysql. But my load_pins method doesn't load any of the data into database, but it does create empty rows for them. I even put a debugger and tried to manually load some data into my pins table so for example
pin = Pin.first
pin.field_id = 1
pin.user_id = 1
pin.save!
and it even returned true, and when I do pin.user_id
it returns 1 but in the database nothing gets saved, or if I just try to print pin it shows empty for everything.
Pin Model:
require_relative '../database_configuration'
class Pin < ActiveRecord::Base
attr_accessor :field_id, :user_id, :board_id, :img_url, :is_repin, :is_video, :source, :link, :description, :user_name
attr_accessible :field_id, :user_id, :board_id, :img_url, :is_repin, :is_video, :source, :link, :description, :user_name
def to_json
{
field_id: field_id,
user_id: user_id,
user_name: user_name,
board_id: board_id,
img_url: img_url,
is_repin: is_repin,
is_video: is_video,
source: source,
link: link,
description: description,
}
end
end
My Load_pins method
def load_pins
pins = JSON.parse(File.read('pins.json'))
Pin.create!(pins)
end
Mysql
mysql> select * from pins;
+----+----------+---------+----------+---------+----------+----------+--------+------+-------------+-----------+
| id | field_id | user_id | board_id | img_url | is_repin | is_video | source | link | description | user_name |
+----+----------+---------+----------+---------+----------+----------+--------+------+-------------+-----------+
| 1 | NULL | NULL | NULL | NULL | 0 | 0 | NULL | NULL | NULL | NULL |
| 2 | NULL | NULL | NULL | NULL | 0 | 0 | NULL | NULL | NULL | NULL |
Any idea why this is happening? Am I missing something when using ActiveRecord outside of Rails?
Upvotes: 2
Views: 310
Reputation: 65467
Remove from attr_accessor
all those that are fields in the pins
table.
If you add validations, you will see that none of your AR fields are being set, because the attr_accessor
is overriding the "fields" that AR uses. AR does not look at the values in instance variables defined by the attr_accessor
, such as @field_id
.
I say "fields" above, because AR actually stores all the field values in an attributes
hash.
Then, AR defines methods to read/write from that hash. So, field_id
is accessible as attributes[:field_id]
and also as the method field_id
.
Upvotes: 2