Mohamed El Mahallawy
Mohamed El Mahallawy

Reputation: 13872

Rails post redirecting to show action and not saving

My code:

    def receive
        @flick = Flick.new(  flick_params )
        if @flick.save
            redirect_to root_path
        else
            redirect_to root_path, notice: "WTF"
        end
    end

    def show

    end

For some reason it's not creating a flick when I call http://localhost:3000/flicks/receive?user_id=asdadasd and instead redirecting me to the show action and doing nothing. Not sure why this is happening.

Thanks!

Upvotes: 0

Views: 49

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

http://localhost:3000/flicks/receive?user_id=asdadasd

That's a GET URL

If you've got to include the user_id as an attached URL param, I'd strongly recommend using something like devise or sessions to give you a way to track the user_id, so you can access it directly in the controller & not pass through the URL


Form

In regards to your question, you need to remember that Rails won't just load the show action for the sake of it. You'll have some problem causing this issue

My suspicion is you're using method: :get in your form (as suggested by Mohanraj). This is a problem, your show and create methods are part of the same routing resource:

GET /photos photos#index    display a list of all photos
GET /photos/new photos#new  return an HTML form for creating a new photo
POST    /photos photos#create   create a new photo
GET /photos/:id photos#show display a specific photo
GET /photos/:id/edit    photos#edit return an HTML form for editing a photo
PATCH/PUT   /photos/:id photos#update   update a specific photo
DELETE  /photos/:id photos#destroy  delete a specific photo

This means if you submit your form with the GET request, you're going to get the show action

Fix

I would recommend trying the answer provided by Mohanraj:

<%= form_for @var do |f| %> #-> this will default to POST
<% end %>

Upvotes: 2

Mohanraj
Mohanraj

Reputation: 4220

If the receive action is a post method, ust specify the method to post in the create form. It should be something like this,

<%= form_for @flick, method: :post do |f| %>
<% end %>

Just try this, it should work.

Upvotes: 2

Related Questions