我正在創建一個庫存應用,其中「分發」是向所有者發佈項目。從rails中的視圖訪問外部表的數據
我distribution.index頁面上,我不能確定如何顯示分配的所有者的名稱(見下文):
<% @distribution.each do |distribution| %>
<tr>
<td><%= distribution.id %></td>
<td><%= (@owner[(distribution.owner_id)]).name %></td>
<td><%= distribution.issued %></td>
<td><%= distribution.returned %></td>
</tr>
<% end %>
錯誤是:未定義的方法'名」的零:NilClass
我明白distribution.owner_id不能解析爲一個讓我找到正確所有者的整數。
控制器:
def index
@distribution = Distribution.all
@item = Item.all
@owner = Owner.all
end
型號:
class Distribution < ActiveRecord::Base
has_one :owner, :class_name => 'Owner', :foreign_key => 'owner_id'
has_one :item, :class_name => 'Item', :foreign_key => 'item_id'
has_one :type, :class_name => 'Type', :foreign_key => 'type_id'
has_one :location, :class_name => 'Location', :foreign_key => 'location_id'
end
class Owner < ActiveRecord::Base
belongs_to :distribution, :class_name => 'Distribution', :foreign_key => 'owner_id'
end
是我的模式設置不正確?:
ActiveRecord::Schema.define(version: 20141030135155) do
create_table "distributions", force: true do |t|
t.integer "item_id"
t.integer "type_id"
t.integer "location_id"
t.integer "owner_id"
t.date "issued"
t.date "returned"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "owners", force: true do |t|
t.string "first"
t.string "last"
t.string "dept"
t.datetime "created_at"
t.datetime "updated_at"
end
我有錯誤:SQLite3 :: SQLException:no such column:owners.distribution_id:SELECT「owners」。* FROM「owners」WHERE「owners」。「distribution_id」=?限制1可能是我的數據庫設置不正確?我看着我的架構,並沒有看到任何參考ID ... – 2014-10-31 18:37:12
您的架構不正確。您需要在所有者表中添加distribution_id列。 – 2014-10-31 18:43:22
也可以在聲明關係時刪除指定的其他屬性,如類和外鍵。 – 2014-10-31 18:44:15