本文介绍了如何在Rails3中将隐藏参数传递给控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将参数 recipient 传递给控制器​​.我可以像这样在我的视图中显示它:

@recipient.username

如何将此值传递给 params[:message][:recipient]?请注意,我没有名为消息"的模型.

controllers/messages_controller.rb

def 交付收件人 = User.find_by_username(params[:recipient])主题 = 参数 [:主题]body = params[:body]current_user.send_message(收件人,正文,主题)重定向到:控制器 =>'消息', :action =>'已收到'flash[:notice] = "消息已发送!"结尾

views/messages/new.html.erb

 :messages, :action => :deliver ) do |f|%><div class="field"><%= f.label :subject%><br/><%= f.text_field :subject %>

<div class="field"><%= f.label :body %><br/><%= f.text_field :body %>

<div class="actions"><%= f.submit %><%结束%>

解决方案

您可以通过为您的 Recipient 分配一个 attr_accessible 键并将其分配给表单来实现.

form_for :message do |f|f.hidden_​​field :recipient_id, :value =>@recipient.id.to_if.text_field :messagef.提交结尾

一旦您将其传递给您的创建操作,您就可以检查 params[:message][:recipient_id]

并将其传递给数据库.

玩得开心

I'd like to pass the parameter recipient to controller. I can show it in my view like this:

@recipient.username

How can I pass this value to params[:message][:recipient]? Note that I do not have a model called "Message".

controllers/messages_controller.rb

def deliver
  recipient = User.find_by_username(params[:recipient])
  subject = params[:subject]
  body = params[:body]

  current_user.send_message(recipient, body, subject)
  redirect_to :controller => 'messages', :action => 'received' 
  flash[:notice] = "message sent!"
end

views/messages/new.html.erb

<td><%= @recipient.username if @recipient %></td>

<%=form_for :messages, url: url_for( :controller => :messages, :action => :deliver ) do |f| %>
  <div class="field">
    <%= f.label :subject %><br />
    <%= f.text_field :subject %>
  </div> 

  <div class="field">
    <%= f.label :body %><br />
    <%= f.text_field :body %>
  </div>

  <div class="actions">
    <%= f.submit %>
<% end %>
解决方案

You could do this by assigning an attr_accessible key for your Recipient and assign it to the form.

form_for :message do |f|
  f.hidden_field :recipient_id, :value => @recipient.id.to_i
  f.text_field :message
  f.submit
end

once you pass this to your create action you are able to check params[:message][:recipient_id]

and pass this to the db.

Have fun

这篇关于如何在Rails3中将隐藏参数传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 10:26