【问题标题】:Strange behavior of rails with link_to带有link_to的rails的奇怪行为
【发布时间】:2019-01-07 15:30:43
【问题描述】:

问题:当我点击 link_to 操作时,应用程序调用另一个控制器导致缺少 id 错误。

我有一个菜单,显示用于创建新对象的按钮,当用户创建对象时,这些按钮将转换为导航链接。

行为是使用 object.exists 吗?帮手。

<div class="nav-wrapper">
  <!-- start menu  -->
  <ul class="nav flex-column">
    <li class="list-group-item"><%= link_to "Personal information", edit_user_registration_path %></li>
    <li class="list-group-item"><%= link_to "Settings", notification_settings_path %></li>
    <li class="list-group-item"><%= link_to "Payments", payment_method_path %></li>
   <% if Prequalification.exists? %>
    <li class="list-group-item"><%= link_to "Edit prequalification",edit_prequalification_path(@user, @prequalification) %></li>
   <% end %>
   <% if Company.exists? %>
    <li class="list-group-item"><%= link_to "Edit company data",edit_company_path(@user, @company) %></li>
   <% end %>
 </ul>
 <ul class="nav flex-column mt-5">
   <% if !Company.exists? %>
    <a class="btn btn-primary btn-block mt-1"  href="companies/new">Add a company</a>
   <% end %>
   <% if !Prequalification.exists? %>
    <a class="btn btn-primary btn-block mt-1"  href="prequalifications/new">Prequalify for loan or rents</a>
    <% end %>
  </ul>
</div>

感谢这篇文章:

https://stackoverflow.com/questions/13186722/what-is-the-difference-between-using-exists-and-present-in-ruby

我可以创建一个新公司并可以访问编辑链接,但是当我随后尝试创建一个资格预审文件时,我得到:

ActionController::UrlGenerationError in Prequalifications#new

No route matches {:action=>"edit", :controller=>"companies", :format=>nil, :id=>nil, :locale=>:en}, possible unmatched constraints: [:id]

公司和资格预审的控制者是分开的。我不明白为什么会发生错误。特别是如果我在执行资格预审之前删除了公司模型的参考链接,那么它似乎可以按预期工作。

我的路线非常简单:

resources :prequalifications
resources :companies

我的控制器也很简单:

def new
 @company = Company.new
end

def create
 @company = current_user.build_company(company_params
end

def edit
 @user = current_user
 @company = Company.find_by(id: [params[:id], params[:company_id]])
end

另一个模型的控制器看起来非常相似。

这种行为可能来自哪里?

【问题讨论】:

    标签: routes ruby-on-rails-5


    【解决方案1】:

    您想测试@company.exists?@prequalification.exists 而不是Company.existsPrequalification.exists,否则您正在测试该类是否存在(总是如此)而不是实际公司和资格预审是否存在。

    这就是您在编辑公司链接时收到错误的原因,因为即使@company = nil 为真,Company.exists 也会尝试为 nil 对象构建链接

    【讨论】:

    • 文森特。谢谢。您的建议正在解决问题(使用 true 和 nil,无法使其与 x.exists 一起使用?我感到惊讶的是,rails 通过调用另一个控制器来构建链接。
    • 它不调用另一个控制器。生成错误是因为 url 生成器在第 11 行获取nil 而不是有效的id,并且您的routes.rb 指出要编辑公司,您需要传递有效的ID。 (因此possible unmatched constraints: [:id]
    猜你喜欢
    • 2016-07-31
    • 1970-01-01
    • 2011-03-16
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2019-08-19
    • 2012-01-10
    相关资源
    最近更新 更多