【发布时间】:2016-07-11 11:47:00
【问题描述】:
所以我正在导入一个 JSON 文件,但是当我去创建对象时,没有生成 id。
这是我的导入方法:
namespace :fieldfacts do
desc "Import Topics"
task :import_topics => :environment do
records = JSON.parse(File.read('public/topics.json'))
records.each do |record|
a = Topic.create
a.name = record['name']
a.save
end
end
end
这是错误:
而且我认为没有 id 就不会保存它。那么我如何在那里获得一个ID?谢谢!
编辑:根据主题模型,我需要通过topics_owners设置一个user_id,但是我该怎么做呢?
主题模型
has_many :topics_owners
has_many :users, -> { uniq }, through: :topics_owners
validates :name, presence: true
validates :user_ids, presence: {:message => "There must be an assigned Topic Owner to continue."}
validates :name, uniqueness: true
控制器
def topic_params
params.require(:topic).permit(:name, :description, :active, [keywords: [:id, :keyword]], [keywords_deleted: [:keyword]], :keywords_list, :keywords_list_deleted,
:organizations_list, :organizations_list_deleted, [organizations: [:id, :organization]], [organizations_deleted: [:organization]],
:social_groups_list, :social_groups_list_deleted, [social_groups: [:id, :social_group]], [social_groups_deleted: [:social_group]],
:feeds_list, :feeds_list_deleted, [feeds: [:id, :feed, :source_url]], [feeds_deleted: [:feed]],
{:articles_list => []}, :articles_list_deleted, :influencers, {:feeds_list => []},
:articles_object, {:feeds_object => []}, :topic_api_id, :read_only, {user_ids: []}, {:influencers_ids => []},
[:people_relevants => [:name, :id, :influencer_id, :topic_id]],
[influencers_adds: [:id, :weight, :influencers_add]], [:influencers_deleted => [:id]], [:influencers_list_deleted => [:id => []]],
[people: [:id, :person, :weight]], [people_deleted: [:person]],
[influencers_topics_attributes: [:influencer_id, :id, :_destroy]], :updater_id, :creator_id,
[influencer_attributes: [:name, :active]])
end
Schema.rb
create_table "topics", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "influencers_topics_count", default: 0, null: false
t.text "description"
t.integer "creator_id"
t.integer "updater_id"
t.boolean "read_only"
t.string "topic_api_id"
t.integer "people_relevants_count"
t.boolean "active", default: false
t.datetime "activation_date"
end
add_index "topics", ["name"], name: "index_topics_on_name", using: :btree
create_table "topics_owners", force: true do |t|
t.integer "topic_id"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "topics_owners", ["topic_id"], name: "index_topics_owners_on_topic_id", using: :btree
add_index "topics_owners", ["user_id"], name: "index_topics_owners_on_user_id", using: :btree
【问题讨论】:
-
你对
Topic模型有任何验证吗? -
这是在主题模型中。 validates :name, presence: true validates :user_ids, presence: {:message => "必须有一个指定的 Topic Owner 才能继续。"} validates :name, uniqueness: true
-
验证是你的问题。启动
rails console并尝试命令。你会看到到底发生了什么。尝试使用a = Topic.new而不是a = Topic.create并在保存之前建立a。 -
酷,我已经尝试过了。谢谢!
-
或者如果您可以在创建过程中传递属性,这可能会为您节省几行代码,例如
Topic.create(name: '...', user_ids: '...')
标签: ruby-on-rails json postgresql activerecord