Ruby-on-rails 将参数从视图传递到控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13672155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:06:49  来源:igfitidea点击:

Passing parameters from view to controller

ruby-on-railsrubyruby-on-rails-3.1controllerparameter-passing

提问by OXp1845

I got a bit of a newbie question. I'm trying to pass a variable from my view to my controller. Is there anyway my method in my controller can receive variables from my view?

我有一个新手问题。我试图将一个变量从我的视图传递给我的控制器。无论如何,我的控制器中的方法可以从我的视图中接收变量吗?

Post view: show.html.erb:
....
<%=link_to "Add relationship", :method => :add_relationship(@rela) %>


Controller: post.controller.rb:

 def add_relationship(rela)
  @post = Post.find(params[:id])

  if current_user.id == @post.user_id
    @post.rel_current_id = rela.id
    @post.save
    redirect_to relationships_url
  else
    redirect_to posts_url, :notice => "FY!"
  end
end

Thanks in advance :)

提前致谢 :)

回答by Steve

You can add information to the params hash right through the link_to. I'm not sure exactly what you are trying to do but I did something like this recently to add the type of email I wanted when I link to the new email

您可以直接通过 link_to 向 params 哈希添加信息。我不确定你到底想做什么,但我最近做了这样的事情,当我链接到新电子邮件时添加我想要的电子邮件类型

<%= link_to 'Send Thanks', new_invoice_email_path(@invoice, :type => "thanks") %>

Now my params looks like:

现在我的参数看起来像:

{"type"=>"thanks", "action"=>"new", "controller"=>"emails", "invoice_id"=>"17"}

I can access the type via the params

我可以通过参数访问类型

email_type = params[:type]

Instead of a string, if you pass in the instance variable @rela you will get the object_id in the params hash.

如果您传入实例变量 @rela,您将获得 params 哈希中的 object_id,而不是字符串。

Per the comment below, I'm adding my routes to show why the path new_invoice_email_path works:

根据下面的评论,我正在添加我的路线以显示路径 new_invoice_email_path 有效的原因:

resources :invoices do
  resources :emails
end

回答by Chris Lewis

When a request comes in, the controller (and any model calls) will be processed first and then the view code gets processed last. The view can call methods in the helpers, but can't reference functions back in the controller.

当一个请求进来时,控制器(和任何模型调用)将首先被处理,然后视图代码最后被处理。视图可以调用助手中的方法,但不能在控制器中引用函数。

However, once a page is rendered, you can either post information back to the controller as part of a new request or use ajax/JQuery (etc) to make a call to a controller function remotely.

但是,一旦页面被呈现,您可以将信息作为新请求的一部分发回控制器,或者使用 ajax/JQuery(等)远程调用控制器功能。

Does that help?

这有帮助吗?