简体   繁体   中英

rails 3 query string params

I try to make a simple message controller with new/create actions, when I call new action I give through query string the to_id param,

/messages/new?to_id=1

that contains id of recipient, now my code is:

def new    
    @message = Message.new    
    @message.to = User.find(params[:to_id])
  end

  def create 
    @message = Message.new(params[:message])
    @message.from = current_user

    respond_to do |format|
      if @message.save
        format.html { redirect_to messages_path }
      else 
        format.html { redirect_to common_error_path, :notice => "failed to send message" }
      end   
    end
  end

It's pretty default, my problem is that the changes in @message object that have been made in new action are not available in create action and I lose my to_id value, the first thing come to my mind is to store to_id value using session object, but I think it's not the best idea, maybe someone have better solution for this

You'll need to pass that parameter back with the POST on create. For example, if you have a

belongs_to :to, :class_name => 'User'

association on your Message model, you could do

app/views/messages/new.html.erb

<%= form_for @message do |f| %>
   <%= f.hidden_field :to_id %>
   ...
<% end %>

The above assumes you've kept your new action the same. Now, on your create action, your params[:message] would be equal to {:to_id => 1} and would assign it properly.

Does that make sense?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM