开发者

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_开发者_StackOverflowid 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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜