怎样使用MySQL和Ruby on Rails开发一个简单的贴吧功能
要使用MySQL和Ruby on Rails开发一个简单的贴吧功能,你可以依照以下步骤进行:
gem install rails
rails new my_forum
cd my_forum
config/database.yml
文件,配置MySQL数据库连接信息。将development和test环境的数据库配置修改成:development:
adapter: mysql2
encoding: utf8
database: my_forum_development
pool: 5
username: your_mysql_username
password: your_mysql_password
host: localhost
test:
adapter: mysql2
encoding: utf8
database: my_forum_test
pool: 5
username: your_mysql_username
password: your_mysql_password
host: localhost
Post
的模型,并生成对应的数据库迁移文件:rails generate model Post title:string content:text
rails db:migrate
app/models/post.rb
文件,并添加以下代码:class Post < ApplicationRecord
has_many :comments
end
Comment
的模型,并生成对应的数据库迁移文件:rails generate model Comment content:text post:references
rails db:migrate
app/models/comment.rb
文件,并添加以下代码:class Comment < ApplicationRecord
belongs_to :post
end
Posts
的控制器:rails generate controller Posts index show new create
Comments
的控制器:rails generate controller Comments create
app/controllers/posts_controller.rb
文件中,添加以下代码:class PostsController < ApplicationController
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
private
def post_params
params.require(:post).permit(:title, :content)
end
end
app/controllers/comments_controller.rb
文件中,添加以下代码:class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
redirect_to @post
end
private
def comment_params
params.require(:comment).permit(:content)
end
end
config/routes.rb
文件,并添加以下代码:Rails.application.routes.draw do
resources :posts do
resources :comments
end
end
rails server
现在你已完成了一个简单的贴吧功能,用户可以创建帖子并对帖子进行评论。你可以进一步根据需求进行功能扩大和界面优化。
TOP