2014-10-31 30 views
0

我正在创建一个库存应用,其中“分发”是向所有者发布项目。从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 

回答

0

既然你已经建立了所有的关系,尝试这样做: -

<td><%= distribution.owner.name %></td> 
+0

我有错误:SQLite3 :: SQLException:no such column:owners.distribution_id:SELECT“owners”。* FROM“owners”WHERE“owners”。“distribution_id”=?限制1可能是我的数据库设置不正确?我看着我的架构,并没有看到任何参考ID ... – 2014-10-31 18:37:12

+0

您的架构不正确。您需要在所有者表中添加distribution_id列。 – 2014-10-31 18:43:22

+0

也可以在声明关系时删除指定的其他属性,如类和外键。 – 2014-10-31 18:44:15

0

如果分布具有或不具有所有者使用:

<td><%= distribution.owner.try(:name) %></td> 

我建议改变你的索引操作,这种方式:

def index 
    @ditributions = Distribution.includes(:owner, :item) 
end 

与分页这做工精细,优化数据库调用。

型号分配必须belongs_to :ownerbelongs_to :item,因为字段owner_id和item_id的存在。更多信息here

相关问题