MySQL과 Ruby on Rails를 사용하여 간단한 블로그 관리 시스템을 개발하는 방법

王林
풀어 주다: 2023-09-20 09:57:17
원래의
1125명이 탐색했습니다.

如何使用MySQL和Ruby on Rails开发一个简单的博客管理系统

MySQL과 Ruby on Rails를 사용하여 간단한 블로그 관리 시스템을 개발하는 방법

개요:
이 글에서는 MySQL과 Ruby on Rails를 사용하여 간단한 블로그 관리 시스템을 개발하는 방법을 소개합니다. 블로그 관리 시스템은 사용자가 블로그 게시물을 작성, 편집 및 관리할 수 있는 일반적인 웹 애플리케이션입니다. 우리는 Ruby on Rails를 개발 프레임워크로, MySQL을 데이터베이스 관리 시스템으로 사용할 것입니다. 데이터베이스 설계, 모델 생성, 컨트롤러 개발 및 뷰 렌더링에 중점을 둘 것입니다. 구체적인 코드 예제는 기사에서 제공됩니다.

1단계: 환경 설정
먼저 Ruby on Rails와 MySQL을 설치하고 구성해야 합니다. 여기서는 구체적인 설치 방법에 대해 자세히 설명하지 않겠습니다. 작동 방법은 공식 문서를 참조하세요. 설치가 완료되면 명령줄을 통해 설치가 성공했는지 확인할 수 있습니다.

2단계: Rails 애플리케이션 생성
다음 명령을 사용하여 새 Rails 애플리케이션 생성:

rails new blog
cd blog
로그인 후 복사

3단계: 데이터베이스 구성
config/database.yml 파일을 열고 찾기 development 섹션을 찾아 다음과 같이 수정하세요. config/database.yml文件,找到development部分,并修改为以下内容:

default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: your_username
  password: your_password
  host: localhost

development:
  <<: *default
  database: blog_development

test:
  <<: *default
  database: blog_test

production:
  <<: *default
  database: blog_production
  username: blog
  password: <%= ENV['BLOG_DATABASE_PASSWORD'] %>
로그인 후 복사

替换your_usernameyour_password为你的MySQL数据库的用户名和密码。

步骤四:创建数据库
运行以下命令来创建数据库:

rails db:create
로그인 후 복사

步骤五:创建博客文章的模型和数据库表
运行以下命令来创建一个名为Post的模型和数据库表:

rails generate model Post title:string content:text
rails db:migrate
로그인 후 복사

以上命令将在app/models目录下创建post.rb文件,以及在数据库中创建一个名为posts的表,其中包含标题(title)和内容(content)两个字段。

步骤六:创建博客控制器
运行以下命令来创建一个名为Posts的控制器:

rails generate controller Posts
로그인 후 복사

以上命令将在app/controllers目录下创建一个posts_controller.rb文件。

步骤七:编写博客控制器的方法
打开app/controllers/posts_controller.rb文件,在类中添加以下方法:

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  def index
    @posts = Post.all
  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
    end
  end

  def update
    if @post.update(post_params)
      redirect_to @post, notice: 'Post was successfully updated.'
    else
      render :edit
    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, :content)
  end
end
로그인 후 복사

以上代码定义了博客控制器的各个动作,如indexshowneweditcreateupdatedestroy。这些动作分别用于展示所有博客文章、展示单篇博客文章、创建新的博客文章、编辑博客文章、保存博客文章的创建或编辑、更新博客文章以及删除博客文章。

步骤八:编写博客视图
打开app/views/posts目录,创建以下文件:

  • index.html.erb:用于显示所有博客文章的列表。
  • show.html.erb:用于显示单篇博客文章的详细内容。
  • new.html.erb:用于创建新的博客文章。
  • edit.html.erb:用于编辑博客文章。

下面是一个简单的示例:

index.html.erb

<h1>Posts</h1>

<% @posts.each do |post| %>
  <h2><%= link_to post.title, post %></h2>
  <p><%= post.content %></p>
<% end %>

<p><%= link_to 'New Post', new_post_path %></p>
로그인 후 복사

show.html.erb

<h1><%= @post.title %></h1>
<p><%= @post.content %></p>

<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
로그인 후 복사

new.html.erb

<h1>New Post</h1>

<%= render 'form' %>

<%= link_to 'Back', posts_path %>
로그인 후 복사

edit.html.erb

<h1>Editing Post</h1>

<%= render 'form' %>

<%= link_to 'Show', @post %> |
<%= link_to 'Back', posts_path %>
로그인 후 복사

_form.html.erb

<%= form_with(model: post, local: true) do |form| %>
  <% if post.errors.any? %>
    <div id="error_explanation">
      <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 class="field">
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>

  <div class="field">
    <%= form.label :content %>
    <%= form.text_area :content %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>
로그인 후 복사

完成以上操作后,我们的简单博客管理系统就可以运行了。运行以下命令启动服务器,然后在浏览器中访问http://localhost:3000/posts

rails server
로그인 후 복사
your_usernameyour_password를 MySQL 데이터베이스 사용자 이름과 비밀번호로 바꾸세요.


4단계: 데이터베이스 생성

다음 명령을 실행하여 데이터베이스를 생성합니다. 🎜rrreee🎜5단계: 블로그 게시물에 대한 모델 및 데이터베이스 테이블 생성 🎜다음 명령을 실행하여 Post라는 모델과 데이터베이스를 생성합니다. 테이블: 🎜rrreee🎜위 명령은 app/models 디렉터리에 post.rb 파일을 생성하고 posts 테이블에는 제목과 내용이라는 두 개의 필드가 포함되어 있습니다. 🎜🎜6단계: 블로그 컨트롤러 만들기🎜다음 명령을 실행하여 <code>Posts라는 컨트롤러를 만듭니다. 🎜rrreee🎜위 명령은 app/controllers 디렉터리에 생성됩니다. posts_controller.rb 파일. 🎜🎜7단계: 블로그 컨트롤러의 메서드 작성 🎜app/controllers/posts_controller.rb 파일을 열고 클래스에 다음 메서드를 추가합니다. 🎜rrreee🎜위 코드는 블로그의 각 작업을 정의합니다. index, show, new, edit, create, 업데이트 및 파기. 이러한 작업은 모든 블로그 게시물 표시, 단일 블로그 게시물 표시, 새 블로그 게시물 생성, 블로그 게시물 편집, 블로그 게시물 생성 또는 편집 내용 저장, 블로그 게시물 업데이트 및 블로그 게시물 삭제에 사용됩니다. 🎜🎜8단계: 블로그 보기 작성 🎜app/views/posts 디렉터리를 열고 다음 파일을 만듭니다: 🎜
  • index.html.erb: 사용됨 모든 블로그 게시물 목록을 표시합니다.
  • show.html.erb: 단일 블로그 게시물의 세부 내용을 표시하는 데 사용됩니다.
  • new.html.erb: 새 블로그 게시물을 작성하는 데 사용됩니다.
  • edit.html.erb: 블로그 게시물을 편집하는 데 사용됩니다.
🎜다음은 간단한 예입니다: 🎜🎜index.html.erb🎜rrreee🎜show.html.erb🎜rrreee🎜new.html.erb🎜rrreee🎜edit.html.erb🎜rrreee🎜 _form .html.erb🎜rrreee🎜위 작업이 완료되면 간단한 블로그 관리 시스템을 실행할 준비가 되었습니다. 다음 명령을 실행하여 서버를 시작한 후 브라우저에서 http://localhost:3000/posts를 방문하세요. 🎜rrreee🎜요약: 🎜이 기사에서는 MySQL과 Ruby를 사용하여 간단한 코드를 개발했습니다. on Rails 블로그 관리 시스템. 데이터베이스 설계, 모델 생성, 컨트롤러 개발 및 뷰 렌더링을 다루었습니다. 위의 단계를 통해 간단한 블로그 관리 시스템을 빠르게 구축하고 더욱 확장하고 최적화할 수 있습니다. 이 기사가 MySQL과 Ruby on Rails를 사용하여 개발하는 방법을 이해하는 데 도움이 되기를 바랍니다. 🎜

위 내용은 MySQL과 Ruby on Rails를 사용하여 간단한 블로그 관리 시스템을 개발하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!