【问题标题】:Rails 4 - Form of expression for a linkRails 4 - 链接的表达形式
【发布时间】: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


【解决方案1】:

实际上 - 我获得代码的方式是正确的。我不得不重置我的数据库并重新开始。一些奇怪的事情导致数据库连接出错。如果其他人在寻找链接,我原来的做法是对的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2016-02-15
    • 2015-07-10
    相关资源
    最近更新 更多