Arw50452
Arw50452

Reputation: 325

Skipping the New Method in Controller (Go Right to the Create Method)

In Rails, I'd like to skip the "new" method in a controller entirely and go directly to the create method. (I don't need any form data to be submitted, and just want to go directly to creating the object based on data from the currently logged in user.)

In rake routes, I don't see a prefix that allows me to link directly to the controller's create method, so I think I should link to the new method and have that redirect to the create action without accepting any input.

I tried doing this with the following:

 def new
    create
 end

 def create
    @request = Request.new
    @request.requestor_id = current_user.id
    @request.status = "S1"
    @request.save

    respond_with(@request, :location => "/products/findexchanges")
 end

When browsing the DB, I can see that this is calling the create action and is adding the record to the db, but after it is done it is redirecting me to new.html.erb rather than the location defined at the end of the create method.

Upvotes: 1

Views: 164

Answers (2)

tenzin dorjee
tenzin dorjee

Reputation: 326

Use button_to instead of link_to. I tried using link_to and even after specifying method: :post, action: :create, it still takes me to index using GET. After using button_to and passing params in ####_path, it directly went to the create method and added data to database. Although I am not sure its correct way or safe way to do this.

Upvotes: 1

Marc-André Lafortune
Marc-André Lafortune

Reputation: 79562

A create action should be triggered by a POST, not GET, which is why there is no specific route for it.

Upvotes: 1

Related Questions