How to pass hidden parameter to controller in Rails3

六月ゝ 毕业季﹏ 提交于 2019-12-12 05:56:19

问题


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 %>

回答1:


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



来源:https://stackoverflow.com/questions/11347646/how-to-pass-hidden-parameter-to-controller-in-rails3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!