Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
不使用Rails的Ruby ActiveRecord不会保存_Ruby_Activerecord - Fatal编程技术网

不使用Rails的Ruby ActiveRecord不会保存

不使用Rails的Ruby ActiveRecord不会保存,ruby,activerecord,Ruby,Activerecord,我有一个Pinterest Ruby爬虫程序(不在Rails中),我将数据写入JSON文件。 我为PIN创建了一个ActiveRecord。我还创建了一个将数据从文件加载到mysql的方法。 但我的load_pins方法不会将任何数据加载到数据库中,但它会为它们创建空行。 我甚至放置了一个调试器,并试图手动将一些数据加载到我的pins表中,例如 pin = Pin.first pin.field_id = 1 pin.user_id = 1 pin.save! 它甚至返回true,当我执行pi

我有一个Pinterest Ruby爬虫程序(不在Rails中),我将数据写入JSON文件。 我为PIN创建了一个ActiveRecord。我还创建了一个将数据从文件加载到mysql的方法。 但我的load_pins方法不会将任何数据加载到数据库中,但它会为它们创建空行。 我甚至放置了一个调试器,并试图手动将一些数据加载到我的pins表中,例如

pin = Pin.first
pin.field_id = 1
pin.user_id = 1
pin.save!
它甚至返回true,当我执行pin.user_id时,它返回1,但在数据库中没有保存任何内容,或者如果我只是尝试打印pin,它显示为空

Pin型号:

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 
Mysql


知道为什么会这样吗?在Rails之外使用ActiveRecord时是否遗漏了什么

attr_accessor
中删除
pins
表中的所有字段

如果添加验证,您将看到没有设置任何AR字段,因为
attr\u访问器
正在覆盖AR使用的“字段”。AR不查看由
属性访问器定义的实例变量中的值,例如
@field\u id

我在上面说“字段”,因为AR实际上将所有字段值存储在
属性
散列中。

然后,AR定义从该散列读取/写入的方法。因此,
field\u id
可以作为
attributes[:field\u id]
访问,也可以作为方法
field\u id

不太可能缺少rails-不要对数据库支持的属性使用attr\u accessor-如果您想了解更多细节,有很多问题与此相关。是的,我不认为缺少rails,我只是说,由于我不熟悉在没有rails的情况下使用ActiveRecord,我可能会遗漏一些东西。那么attr_访问器会有什么问题?例如,可能与See重复
def load_pins
  pins = JSON.parse(File.read('pins.json'))
  Pin.create!(pins)
end
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      |