简体   繁体   中英

Issue with Rails link_to if method

In my Ruby on Rails application I have method that looks like this:

  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:

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:

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:

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

The solution is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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