从api保存数据(但只保存一次)

时间:2016-07-01 13:41:12

标签: ruby-on-rails database api validation rails-activerecord

我想保存API中的数据,但只需保存一次。目前它每次重新加载我的页面时都会保存数据,因此我有相同的条目次数...我只是想保存新的,如果它们。 当我尝试添加验证以避免这种情况时,我收到此错误:

  

验证失败:已经过了日期,已经使用了Url

这是我的代码:

架构:

 create_table "conferences", force: :cascade do |t|
  t.string   "title",      null: false
  t.string   "url"
  t.date     "date",       null: false
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

conference.rb:

class Conference < ActiveRecord::Base
validates_presence_of :title, :date
validates :date, :url, :uniqueness => true

 def self.save_conference_from_api
  response = ApiMeetup.new.events('parisrb')
  api_data = JSON.parse(response.body)
  parisrb = []
  api_data.each do |event|
    if event["name"] == "ParisRb.new(premier: :mardi, pour: :talks)"
      parisrb << event
    end
  end
  parisrb.map do |line|
    conference = Conference.new
    conference.title = line['name']
    conference.date = line['time']
    conference.url = line['link']
    conference.save!
  end
  Conference.all
 end
end

meetings_controller:

def index
  @conferences = Conference.save_conference_from_api
end

索引:

%ul
  - @conferences.each do |conf|
    %li
      %span
        = conf.date

1 个答案:

答案 0 :(得分:1)

如果它无效,请不要保存

conference.save!

变为

if conference.valid? conference.save!

因为保存!提出一个ActiveRecordValidation错误然后你可以陷阱而不是你真的不需要!如果在保存之前检查有效记录,请在保存方法上

所以你可以拥有

begin
  conference.save!
rescue ActiveRecord::RecordInvalid => invalid
  # Do nothing
end

或者你真的应该

if conference.valid? conference.save

如果所有记录都在一个数组中,那么你的html模板可以迭代遍历数组并根据需要显示每个记录的错误。