简体   繁体   English

将参数从视图传递到控制器

[英]Passing parameters from view to controller

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 :) 提前致谢 :)

You can add information to the params hash right through the link_to. 您可以直接通过link_to将信息添加到params哈希中。 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 '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

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? 有帮助吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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