怎样使用MySQL和Ruby on Rails开发一个简单的贴吧功能
要使用MySQL和Ruby on Rails开发一个简单的贴吧功能,你可以依照以下步骤进行:
gem install railsrails new my_forumcd my_forumconfig/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: localhostPost的模型,并生成对应的数据库迁移文件:rails generate model Post title:string content:textrails db:migrateapp/models/post.rb文件,并添加以下代码:class Post < ApplicationRecord
has_many :comments
endComment的模型,并生成对应的数据库迁移文件:rails generate model Comment content:text post:referencesrails db:migrateapp/models/comment.rb文件,并添加以下代码:class Comment < ApplicationRecord
belongs_to :post
endPosts的控制器:rails generate controller Posts index show new createComments的控制器:rails generate controller Comments createapp/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
endapp/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
endconfig/routes.rb文件,并添加以下代码:Rails.application.routes.draw do
resources :posts do
resources :comments
end
endrails server现在你已完成了一个简单的贴吧功能,用户可以创建帖子并对帖子进行评论。你可以进一步根据需求进行功能扩大和界面优化。
TOP