将参数从视图传递到控制器 [英] Passing parameters from view to controller

查看:184
本文介绍了将参数从视图传递到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个新手问题。我试图传递一个变量从我的视图到我的控制器。是否还有我的方法在我的控制器中可以从我的视图接收变量?

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

提前感谢:)

推荐答案

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

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 'Send Thanks', new_invoice_email_path(@invoice, :type => "thanks") %>

现在我的参数如下:

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

我可以通过params访问类型

I can access the type via the params

email_type = params[:type]

字符串,如果你传递的实例变量@rela你会得到params哈希中的object_id。

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

根据下面的注释,我添加我的路由, new_invoice_email_path的工作路径:

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

resources :invoices do
  resources :emails
end

这篇关于将参数从视图传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆