Ruby 2.3.0、Rails 4.2.4、PostgreSQL 9.5
更新:在下面添加了 activerecord-import 代码。
有谁知道如何使这些关联保持不变,以便可以在另一个视图中引用模型的表属性?类似于另一个问答(Rails has_many 通过使用 source 和 source_type 对多种类型进行别名),其中我有投资者、公司和交易。
我已经尝试过类似下面的关联 ( has_many ... through ...
),但我无法让 ActiveRecord 识别 3 个模型和表之间的连接。播种数据库:
数据进入这些表的方式是通过具有 3 列的 csv 文件。我使用 roo-xls 将每个提取到一个数组数组中。
我的基于activerecord-import gem的代码(每个 *_val 是一个由 1000 个数组组成的数组):
icol = [:name]
ccol = [:name]
tcol = [:investor_name, :company_name, :percent_owned]
investor_val = [["i1"],["i2"]] # just showing 2 arrays for brevity
company_val = [["c1"],["c2"]] # ""
transaction_val = [["i1","c1","pct1"],["i2","c2","pct2"]] # ""
Investor.import icol, investor_val, :validate => false
Company.import ccol, company_val, :validate => false
Transaction.import tcol, transaction_val, :validate => false
导入有效,但是当我检查transactions
表格时,执行 activerecord-import 后company_id 和investor_id.import
都为零。我当然希望它们包含用于company
和investor
模型记录的外键。
我的模型如下。
Class Company < ActiveRecord::Base
has_many :investors,
:through => :transactions
has_many :transactions
end
Class Investor < ActiveRecord::Base
has_many :companies,
:through => :transactions
has_many :transactions
end
Class Transaction < ActiveRecord::Base
belongs_to :company
belongs_to :investor
end
交易迁移(其他为简洁起见)
class CreatePositions < ActiveRecord::Migration
def change
create_table :positions do |t|
t.string :investor_name
t.string :company_name
t.string :percent_owned
t.belongs_to :company, index: true
t.belongs_to :manager, index: true
t.timestamps null: false
end
end
end
我的schema,我在其中添加了对belongs_to
( transactions
) 表的引用。
ActiveRecord::Schema.define(version: 20160128224843) do
create_table "companies", force: :cascade do |t|
t.string "name"
t.string "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "investors", force: :cascade do |t|
t.string "name"
t.string "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "transactions", force: :cascade do |t|
t.string "investor_name"
t.string "company_name"
t.float "percent_owned"
t.integer "investor_id"
t.integer "company_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "transactions", ["investor_id"], name: "index_transactions_on_investor_id", using: :btree
add_index "transactions", ["company_id"], name: "index_transactions_on_company_id", using: :btree