简体   繁体   English

如何通过Rails中的url将参数发送到另一个控制器的动作?

[英]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.idnew的动作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.

相关问题 Rails通过不同对象的形式将参数从一个控制器动作传递到另一个 - Rails pass parameter from one controller action to another through form of different object 如何在 controller 中不使用 Rails 动作参数 - How to not use Rails action parameter in controller 如何在Rails中将格式参数发送到show动作 - How to send a format parameter to a show action in Rails Rails,通过link_to向控制器动作发送参数 - Rails, send params to controller action through link_to 如何通过link_to helper从rails中的视图传递参数到控制器操作 - How to pass a parameter to controller action from view in rails through link_to helper 如何显示一个控制器在导轨中的另一个控制器动作中显示动作 - how to display one controller show action in another controller action in rails 如何在 Rails 中访问 URL 在 Controller 中显示操作 - How to access URL in Rails Show action in Controller Rails:如何将参数从视图发送到控制器 - Rails: How to send parameter from View to Controller 如何设置Rails路由以使用参数和默认操作将某些URL重定向到另一个控制器? - How can I set rails routes to redirect some urls to another controller with parameter and default action? Rails:如何在内部POST到另一个控制器动作? - Rails: How to POST internally to another controller action?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM