我对Rails很新。我想要做的是访问销售的分支名称和产品名称。我指定了三个模型(销售,分公司,产品)的协会。但是,我无法检索值。在“index.html.erb”视图中,它显示分支名称和产品名称的nil值。如何访问这些值?
sale.rb
class Sale < ActiveRecord::Base
belongs_to :branch, :class_name => "Branch", :foreign_key => :branch_code
belongs_to :product, :class_name => "Product", :foreign_key => :product_sku
end
branch.rb
class Branch < ActiveRecord::Base
has_many :sales, :class_name => "Sale", :foreign_key => :branch_code
end
product.rb
class Product < ActiveRecord::Base
has_many :sales, :class_name => "Sale", :foreign_key => :product_sku
end
index.html.erb
<h1>Sales Index</h1>
<h2>Files in database</h2>
<table border=2>
<tr>
<th>Branch Name</th>
<th>Product Name</th>
<th>Qty. Sold</th>
<th>End of day Qty</th>
<th>Date</th>
<th>Date Created</th>
<th>Date Last Modified</th>
</tr>
<% @sales.each do |sale| %>
<tr>
<td><%= sale.branch %></td>
<td><%= sale.product %></td>
<td><%= sale.quantity_sold %></td>
<td><%= sale.end_of_day_quantity %></td>
<td><%= sale.salesdate %></td>
<td><%= sale.created_at %></td>
<td><%= sale.updated_at %></td>
</tr>
<% end %>
</table>
sales_controller.rb
class SalesController < ApplicationController
def index
@files = Dir.glob('/Users/xxyy/Documents/rails/Dummy/*.csv')
#@mapper = Array.new()
require 'csv'
require 'fileUtils'
for file in @files
filename = File.basename(file, ".*")
date = filename[22..31]
csv_text = File.read(file)
CSV.foreach(file, :headers => true) do |row|
Sale.create(:branch_code => row[0], :product_sku => row[1], :quantity_sold => row[2], :end_of_day_quantity => row[3], :salesdate => date)
end
FileUtils.mv(file, '/Users/xxyy/Documents/rails/Read/')
end
@sales = Sale.all
end
end
schema.rb
ActiveRecord::Schema.define(version: 20140812013013) do
create_table "branches", force: true do |t|
t.string "branch_code"
t.string "branch_name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "products", force: true do |t|
t.string "product_sku"
t.string "product_name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "sales", force: true do |t|
t.string "branch_code"
t.string "product_sku"
t.integer "quantity_sold"
t.integer "end_of_day_quantity"
t.integer "branch_id"
t.integer "product_id"
t.datetime "created_at"
t.datetime "updated_at"
t.datetime "salesdate"
end
add_index "sales", ["branch_id"], name: "index_sales_on_branch_id"
add_index "sales", ["product_id"], name: "index_sales_on_product_id"
end
答案 0 :(得分:0)
确保您已正确完成关联。
class Product < ActiveRecord::Base
has_many :sales, :class_name => "Sale", :foreign_key => :product_sku
end
答案 1 :(得分:-2)
has_many :sales
这需要是复数。
class Branch < ActiveRecord::Base
has_many :sales
end
你不需要在这里指定类名,外键应该是branch_id(我猜测),也不需要指定。