mercredi 31 mai 2023

submit button doesnot lead back to index in Ruby on Rails

I am new to Ruby on rails and i was trying to figure out where my code is failing. I created an Articles table so when i go to articles/new where if have the view to create article after i click on submit button it doesnot go to /articles but in terminal, it shows that a post request was made.

I have created a table articles and Model Article along with article_controller class also in the routes i have added resources :articles

But when i visit to articles/new and create a new article using the form i can see the create fn in the controller is called due to the POST request on article_path (/articles/) (because i tried to save the article into db and it did got saved) but when i try to display the article details using render plain: @articles.inspect nothing happens and it remains on /articles/new even after hitting the submit button (even if the create fn in empty it stays on that page). Please Help!

Controller

class ArticlesController < ApplicationController
    def show
        @article = Article.find(params[:id])
    end
    def index
        @articles = Article.all()
    end
    def new

    end
    def create
        render plain: @article.inspect
    end
end

Model

class Article < ApplicationRecord
    validates :title, presence: true, length: {minimum: 3, maximum: 50}
    validates :description, presence: true, length: {minimum: 10, maximum: 100}
end

New Form

<h1>Create an Article <h1>
<%= form_with scope: :article, url: articles_path, method: :post, local: true do |f| %>
    <p>
        <%= f.label :title %><br/>
        <%= f.text_field :title %>
    </p>
    <p>
        <%= f.label :description %><br/>
        <%= f.text_area :description %>
    </p>
    <p>
        <%= f.submit %>
    </p>
<% end %>

Index Page

<h1>Showing All Articles</h1>

<table>
    <thead>
        <tr>
            <th>Title</th>
            <th>Description</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <% @articles.each do |article|%>
            <tr>
                <td><%= article.title%></td>
                <td><%= article.description%></td>
                <td>PlaceHolder</td>
            </tr>
        <% end %>
    </tbody>
</table>

Aucun commentaire:

Enregistrer un commentaire