怎样使用MySQL和Ruby on Rails开发一个简单的在线投票系统
要使用MySQL和Ruby on Rails开发一个简单的在线投票系统,需要遵守以下步骤:
rails new voting_system
config/database.yml
文件,并将其配置为连接到MySQL数据库。确保使用正确的用户名、密码和数据库名称。rails generate model Poll title:string
rails generate model Option poll:references option_text:string
rails generate model Vote poll:references option:references
rails db:migrate
app/models/poll.rb
文件,并添加以下代码:class Poll < ApplicationRecord
has_many :options
has_many :votes, through: :options
end
打开app/models/option.rb
文件,并添加以下代码:
class Option < ApplicationRecord
belongs_to :poll
has_many :votes
end
打开app/models/vote.rb
文件,并添加以下代码:
class Vote < ApplicationRecord
belongs_to :poll
belongs_to :option
end
rails generate controller Polls
打开app/controllers/polls_controller.rb
文件,并添加以下代码:
class PollsController < ApplicationController
def index
@polls = Poll.all
end
def show
@poll = Poll.find(params[:id])
end
end
app/views/polls
文件夹中创建index.html.erb
和show.html.erb
视图文件,并使用适当的代码来显示投票系统的数据。config/routes.rb
文件,并添加以下代码:Rails.application.routes.draw do
resources :polls, only: [:index, :show]
root to: 'polls#index'
end
rails server
http://localhost:3000
来访问投票系统。以上是使用MySQL和Ruby on Rails开发一个简单的在线投票系统的基本步骤。你可以根据实际需求对模型、控制器和视图进行定制和扩大。
TOP