create a link_to in controller

2020-05-26 16:35发布

问题:

I need to pass a notice to a view from controller, and I want if can to create some link also to the notice.

My controller:

format.html { redirect_to purchase_order_headers_path, notice: 'PO already has RR with RR ID: ' + rr.rr_id + ', void RR first.' }

Is there any way so I can do it so the [rr.rr_id] will become a link so when the user click on it will go to it's page? Since link_to will return error "undefined method" if put on controller.

Thanks.

回答1:

if you are using rails 3, you can use view_context.link_to(...) in your controller.

UPDATE: with the format.html code

format.html do
  redirect_to purchase_order_headers_path, notice: "PO already has RR with RR ID: #{view_context.link_to(rr.rr_id, receiving_record_header_path(rr.id))} void RR first.".html_safe
end


回答2:

Use #{ActionController::Base.helpers.link_to 'rr.rr_id', '/url'}.html_safe

To make link in your controllers. To have the string display as html (instead of being escaped), call the html_safe method on the string