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
POSTon create. For example, if you have abelongs_to :to, :class_name => 'User'association on your
Messagemodel, you could doapp/views/messages/new.html.erbThe above assumes you’ve kept your
newaction the same. Now, on yourcreateaction, yourparams[:message]would be equal to{:to_id => 1}and would assign it properly.Does that make sense?