SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Member
    Join Date
    Jun 2007
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    GET/POST controller question

    I'm curious about the following code...

    Code:
    class StoryController < ApplicationController
      def new
        @story = Story.new(params[:story])
        if request.post? and @story.save
          flash[:notice] = 'Story submission succeeded'
          redirect_to :action => 'index'
        end
      end
    end
    What's happening with the underlined line when the controller receives a GET? There isn't anything in the params hash right? I'm guessing it makes an empty story, but isn't that kind of a waste unless I actually need one (when the request is a POST)?

  2. #2
    SitePoint Member
    Join Date
    Jun 2007
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PS - I'm following the Lenz Rails book, that's why I don't understand my own code! =)

  3. #3
    SitePoint Wizard samsm's Avatar
    Join Date
    Nov 2001
    Location
    Atlanta, GA, USA
    Posts
    5,011
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you want to see what is in params on a given request, do:

    <&#37;= debug params %> in a view.

    However you are correct, in the case of a GET, params[:story] is probably nil, though it certainly would be possible to pump it full of values through the query string.

    It isn't much of a waste. Creating the story object is a standard part of the Rails "new" process ... the model gets used to help shape the form. Until @story.save, nothing happens in the database.
    Using your unpaid time to add free content to SitePoint Pty Ltd's portfolio?

  4. #4
    SitePoint Guru silver trophy Luke Redpath's Avatar
    Join Date
    Mar 2003
    Location
    London
    Posts
    794
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    BTW, the most up-to-date Rails REST-style convention is to have separate actions for new and create - create is called by using POST.

  5. #5
    SitePoint Guru Skyblaze's Avatar
    Join Date
    Jul 2005
    Location
    Italy
    Posts
    734
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    a @story instance variable is required for form_for helper in the view to work correctly, even if it is a story object with empty/nil attributes.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •