简体   繁体   English

Rails link_to if方法出现问题

[英]Issue with Rails link_to if method

In my Ruby on Rails application I have method that looks like this: 在我的Ruby on Rails应用程序中,我具有如下所示的方法:

  def survey_pack_signed_off(sp, type)
    signed_off = Util::Boolean.humanize(sp.survey_pack_sign_off.present?)#returns Yes if true and No if false
    return signed_off if type == :csv
    if sp.survey_pack_sign_off.present?
      link_to signed_off, admin_survey_pack_sign_off_path(sp.survey_pack_sign_off)
   else
     signed_off
  end
end

I was trying to refactor it and use Rails link_to_if method: 我试图对其进行重构,并使用Rails link_to_if方法:

def survey_pack_signed_off(sp, type)
  signed_off = Util::Boolean.humanize(sp.survey_pack_sign_off.present?)#returns Yes if true and No if false
  return signed_off if type == :csv
  link_to_if (type == :html && sp.survey_pack_sign_off.present?), signed_off,   admin_survey_pack_sign_off_path(sp.survey_pack_sign_off)
end

But this link_to_if causes following error: 但是此link_to_if导致以下错误:

ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"admin/survey_pack_sign_offs", :format=>nil, :id=>nil} missing required keys: [:id]

Why this code not works? 为什么此代码不起作用?

Try to set id explicitly: 尝试显式设置id

admin_survey_pack_sign_off_path(id: sp.survey_pack_sign_off)

If I correctly understood your code and survey_pack_sign_off contains some id of the page 如果我正确理解您的代码,并且survey_pack_sign_off包含页面的某些ID

The solution is: 解决方案是:

  spso = sp.survey_pack_sign_off
  link_to_if spso, signed_off, spso ? admin_survey_pack_sign_off_path(spso) : nil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM