[英]how to send parameter to the action of another controller through url in rails?
How to send parameter to the action of another controller through url in rails? 如何通过Rails中的url将参数发送到另一个控制器的动作?
controller1: 控制器1:
def show
@controller1.id = params[:controller1_id]
end
in the view of controller1: 在controller1的视图中:
%a.btn-general{:href => "/controller2/new/#{parameteroffirst.id}", :controller1_id @controller1.id, :role => "button"} Add the first
how to send controller1.id
to new
action of controller2
? 如何发送
controller1.id
到new
的动作controller2
?
If you really want to write it out like this, try changing: 如果您真的想这样写出来,请尝试更改:
:href => "/controller2/new/#{parameteroffirst.id}", :controller1_id @controller1.id
To: 至:
:href => "/controller2/new?controller1_id=#{parameteroffirst.id}"
But it's really worth your reading up on how links are supposed to work in ruby / rails: 但是,真正值得一读的是链接应该如何在ruby / rails中工作:
https://api.rubyonrails.org/v5.2.1/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to https://api.rubyonrails.org/v5.2.1/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
A good practice in rails is to use named routes instead of string urls. Rails中的一个好习惯是使用命名路由而不是字符串url。
%a.btn-general{href: url_for(controller: :controller2, action: :new, id: parameteroffirst.id, controller1_id: @controller1.id), role: "button"} Add the first
It will generate an url like /controller2/new/#{parameteroffirst.id}?controller1_id=#{@controller1.id}
. 它将生成一个类似于
/controller2/new/#{parameteroffirst.id}?controller1_id=#{@controller1.id}
的网址。 but you can change the route tomorrow without the need to go all over your code changing the hardcoded links. 但是您明天就可以更改路线,而无需遍历所有代码来更改硬编码链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.