0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Reactとの連携(4)

Posted at
rails g model data name:text mail:text

dataの複数形で単数形はdatumです。

モデルを用意してバリデーションを設定します。
内容はnameが空でないこととメールがからでないこと

class Datum < ApplicationRecord
  validates :name, presence: true
  validates :mail, presence: true
end

テーブル設定してマイグレーションします。

2021050293420_create_data.rb
class CreateData < ActiveRecord::Migration[6.0]
  def change
    create_table :data do |t|
      t.text :name
      t.text :mail

      t.timestamps
    end
  end
end

ダミーデータを3件ほど入力します。

db/seed.rb
Datum.create(id:1, name:'Taro', mail:'taro@yamada')
Datum.create(id:2, name:'Hanako', mail:'hanako@flower')
Datum.create(id:3, name:'Sachiko', mail:'sachiko@happy')
terminal
rails db:seed

実行します。

terminal
rails g controller data index ajax

コントローラを作ります。

app/controllers/data_controller.rb
class DataController < ApplicationController
  def index
  end

  def ajax
    if params[:name] then
      data = Datum.where 'name like ?', "%" + params[:name] + '%'
    else
      data = Datum.all
    end
    render plain:data.to_json
  end
end

jsonデータとしてとり出してrender plainでテキストとして送信します。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?