Prompt:
test app
# TODO: Generate Rails MVC components for the provided description: "test app". # Insufficient domain details were provided to accurately model entities and relationships. # A minimal scaffold-style setup is provided below as a starting point. # app/models/post.rb class Post < ApplicationRecord validates :title, presence: true validates :body, presence: true end # db/migrate/xxxxxx_create_posts.rb class CreatePosts < ActiveRecord::Migration[7.1] def change create_table :posts do |t| t.string :title, null: false t.text :body, null: false t.timestamps end end end # app/controllers/posts_controller.rb class PostsController < ApplicationController before_action :set_post, only: %i[ show edit update destroy ] def index @posts = Post.order(created_at: :desc) end def show end def new @post = Post.new end def edit end def create @post = Post.new(post_params) if @post.save redirect_to @post, notice: 'Post was successfully created.' else render :new, status: :unprocessable_entity end end def update if @post.update(post_params) redirect_to @post, notice: 'Post was successfully updated.' else render :edit, status: :unprocessable_entity end end def destroy @post.destroy! redirect_to posts_url, notice: 'Post was successfully destroyed.' end private def set_post @post = Post.find(params[:id]) end def post_params params.require(:post).permit(:title, :body) end end # app/views/posts/index.html.erb <h1>Posts</h1> <%= link_to 'New Post', new_post_path %> <ul> <% @posts.each do |post| %> <li> <%= link_to post.title, post %> <small>(<%= time_ago_in_words(post.created_at) %> ago)</small> </li> <% end %> </ul> # app/views/posts/show.html.erb <p> <strong>Title:</strong> <%= @post.title %> </p> <p> <strong>Body:</strong> <%= simple_format(@post.body) %> </p> <%= link_to 'Edit', edit_post_path(@post) %> | <%= link_to 'Back', posts_path %> # app/views/posts/new.html.erb <h1>New Post</h1> <%= render 'form', post: @post %> # app/views/posts/edit.html.erb <h1>Edit Post</h1> <%= render 'form', post: @post %> # app/views/posts/_form.html.erb <%= form_with(model: post) do |form| %> <% if post.errors.any? %> <div style="color: red"> <h2><%= pluralize(post.errors.count, 'error') %> prohibited this post from being saved:</h2> <ul> <% post.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div> <%= form.label :title %><br> <%= form.text_field :title %> </div> <div> <%= form.label :body %><br> <%= form.text_area :body, rows: 8 %> </div> <div> <%= form.submit %> </div> <% end %> # config/routes.rb (add resource route) Rails.application.routes.draw do resources :posts end
Edit
|
Back
Destroy