Ruby on Rails is a powerful web application framework that provides a convenient way to interact with databases. When working with SQL Server as your database management system, it’s crucial to understand how to define database models and manage schema changes using Rails migrations. In this article, we’ll walk through the process of creating database models and migrations in Rails application while using SQL Server as our database backend.
前提条件
- Ruby on Rails installed on your system.
- A SQL Server instance set up and accessible.
Creating a New Rails Application
Let’s start by creating a new Rails application. Open your terminal and run the following command:
rails new sql_server_rails_app
This command will generate a new Rails application named sql_server_rails_app
. Navigate to the project directory:
cd sql_server_rails_app
To configure SQL Server as the database, open the config/database.yml
file and modify it as follows:
デフォルト: &デフォルト adapter: sqlserver host: localhost username: your_username password: your_password database: your_database_name port: 1433
Replace your_username
, your_password
、 そして your_database_name
with your SQL Server credentials and the desired database name.
Creating a Database Model
Let’s create a simple database model for a blog application. Run the following command to generate a 役職
model with attributes:
rails generate model Post title:string body:文章
This command will create a migration file in the データベース/移行
directory and a corresponding model file in the app/models
ディレクトリ。
Creating a Migration
Open the generated migration file in the データベース/移行
directory. It will have a name like xxxxxx_create_posts.rb
, where xxxxxx
is a timestamp. Add the necessary columns to the create_table
block:
class CreatePosts < アクティブレコード::Migration[6.1] def change create_table :posts do |t| t.string :title t.文章 :body t.timestamps 終わり 終わり 終わり
This migration creates a posts
table with タイトル
そして body
columns.
Running Migrations
To apply the migration and create the posts
table in the SQL Server database, run the following command:
rails db:migrate
This command will execute all pending migrations and update the database schema accordingly.
Using the Model
Now that the 役職
model and table are created, you can use it in your Railsアプリケーション. For example, you can create a new post in your controller:
class PostsController < ApplicationController def 作成する @post = 役職.new(post_params) if @post.save redirect_to @post, notice: 'Post was successfully created.' それ以外 render :new 終わり 終わり private def post_params params.必要とする(:post).permit(:タイトル, :body) 終わり 終わり
結論
In this blog post, we’ve learned how to create database models and migrations in a Ruby on Rails application using SQL Server as the database backend. You can now start building your application with the power and flexibility of Rails while leveraging the capabilities of SQL Server for data storage and retrieval.