【发布时间】:2016-04-15 04:46:41
【问题描述】:
我正在尝试在 Rails 4 中制作应用程序。
我有一个档案模型和一个组织模型。组织有一个名为“title”的属性。
关联是:
Profile belongs_to organisation
Organisations has_many profiles
我正试图弄清楚如何编写从我的个人资料显示页面到组织显示页面的链接。
我觉得这是正确的:
<%= link_to @profile.organisation.try(:title).upcase, organisation_path(@profile.organisation.id) %>
但是,当我尝试时,我得到了这个错误:
undefined method `id' for nil:NilClass
我可以在控制台中看到 profile.organisation id 不是 nil - 它有一个值。
谁能看到我做错了什么?
rake 路线 - 用于组织:
organisations GET /organisations(.:format) organisations#index
POST /organisations(.:format) organisations#create
new_organisation GET /organisations/new(.:format) organisations#new
edit_organisation GET /organisations/:id/edit(.:format) organisations#edit
organisation GET /organisations/:id(.:format) organisations#show
PATCH /organisations/:id(.:format) organisations#update
PUT /organisations/:id(.:format) organisations#update
DELETE /organisations/:id(.:format) organisations#destroy
【问题讨论】:
-
试试这个
@profile.organisation而不是这个@profile.organisation.id -
如果我从该行的末尾删除 id,我会收到此错误:No route matches {:action=>"show", :controller=>"organisations", :id=>nil}缺少必需的键:[:id]
-
告诉我你的
rake routes和模型关联.. -
已更新以将它们添加到上方。
-
那个特定的
profile没有与之关联的organisation,所以是错误。
标签: ruby-on-rails associations link-to