开发者

Rails, redirect from NEW to CREATE

开发者 https://www.devze.com 2023-01-26 16:21 出处:网络
Hey all, I\'m writing an app to handle registration for athletic events. Some of these events have multiple athletes per entry, while some have only a single athlete. I\'m currently sending the athlet

Hey all, I'm writing an app to handle registration for athletic events. Some of these events have multiple athletes per entry, while some have only a single athlete. I'm currently sending the athlet开发者_如何学编程e to the NEW action on BoatsController like so:

<%= link_to 'Register', new_event_boat_path(@event) %>

My question is, if the NEW action sees that the event only requires one user per boat, how can I forward the user directly to the CREATE action? More concisely, how can I generate a POST from within an action?


You dont need to do anything fancy. The create action is just a method in your controller. You can call it just like any other method:

def new
   if event_only_requires_one_user_per_boat
       create
   else
      #display new form
   end
end

Also, this technique prevents the user from having to make multiple requests since it doesn't make the user redirect.


You could instead create a method that encapsulates most of the code from your create action, and invoke it from create (with params as usual) and from your special case in new (sending in data from your user object).


def new
   #assuming boats is an array 
   if boats.size > 1
       redirect_to boats_path(:user => params[:user], :boat => params[:boat]), :method => :post
   else
      #new stuff
   end
end

boats_path or whatever object you are trying to create.

0

精彩评论

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