问题
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