• Right now, we're pointing the form to an update action, which isn't defined yet, but we'll do that soon.

     

    Passing an article object to the method will automatically generate a url to submit the edited article form. This option tells Rails that we want this form to be submitted using PATCH, an HTTP method that is expected to be used to update resources according to the REST protocol.

     

    The form_with arguments can be model objects, such as model: @article , which will cause the helper to populate the form with the object's fields. Passing a symbol (scope: :article) to the namespace just creates the fields, but doesn't populate them with anything. Read more in the form_with documentation.

     

    Next, we need to create an update action in app/controllers/articles_controller.rb. Add it between the create action and the private method:

     

    def create

      @article = Article.new(article_params)

     

      if @article.save

        redirect_to @article

      else

        render 'new'

      end

    end


    votre commentaire
  •  

     

    A few things about what's going on. We check if there are any errors with @article.errors.any?, in which case we show a list of all errors with @article.errors.full_messages.

     

    pluralize is a rails helper that takes a number and a string as arguments. If the number is greater than one, the string will be automatically pluralized.

     

    The reason we added @article = Article.new to the ArticlesController is because otherwise @article would be nil in the view, and calling @article.errors.any? will cause an error.

     

    TIP: Rails automatically wraps errored fields in a div with class field_with_errors. You can define a css rule to make them stand out.

     

    Now we'll have a nice error message when saving an article without a title if we try this in the new article form http://localhost:3000/articles/new.

     

    Form with errors

     

     

    We have revealed the "CR" part of CRUD. Now let's focus on the "U" part, updating articles.

     

    The first step is to add an edit action to the ArticlesController, usually between the new and create actions, as shown.


    votre commentaire



    Suivre le flux RSS des articles
    Suivre le flux RSS des commentaires