【问题标题】:How to pass hidden parameter to controller in Rails3如何在 Rails3 中将隐藏参数传递给控制器
【发布时间】:2012-07-05 15:30:46
【问题描述】:

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

@recipient.username

如何将此值传递给params[:message][:recipient]?请注意,我没有名为“Message”的模型。

控制器/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

视图/消息/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 %>

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3 view parameter-passing


【解决方案1】:

您可以通过为您的收件人分配一个 attr_accessible 密钥并将其分配给表单来做到这一点。

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

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

并将其传递给数据库。

玩得开心

【讨论】:

    猜你喜欢
    • 2012-11-16
    • 1970-01-01
    • 2017-03-07
    • 2014-02-22
    • 2018-07-14
    • 1970-01-01
    • 2022-10-31
    • 1970-01-01
    相关资源
    最近更新 更多