【发布时间】:2016-07-01 13:41:12
【问题描述】:
我想保存 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
会议控制器:
def index
@conferences = Conference.save_conference_from_api
end
索引:
%ul
- @conferences.each do |conf|
%li
%span
= conf.date
【问题讨论】:
-
您的验证工作正常,那么到底是什么问题?他们正在阻止创建记录并告诉您。
-
是的,验证有效,但那时我无法访问该站点。那么我怎么能说“好吧它存在所以什么都不做,去检查下一个,然后显示页面”
标签: ruby-on-rails database api validation rails-activerecord