class CreateAnnouncements < ActiveRecord::Migration
def change
create_table :announcements do |t|
t.string :subject, :null => false
t.text :content
t.timestamps
end
end
end
次にマイグレーションをします。
def change
create_table :announcements do |t|
t.string :subject, :null => false
t.text :content
t.timestamps
end
end
end
$ rake db:migrate
次にseeds.rbを設定
table_names = %w(announcements)
table_names.each do |table_name|
dir = case Rails.env
when 'development', 'staging'
'development'
when 'production'
'production'
end
path = Rails.root.join('db', 'seeds', dir, "#{table_name}.rb")
if File.exist?(path)
puts "Creating #{table_name}..."
require(path)
end
end
seedsフォルダを作成しその下にdevelopmentフォルダを作成table_names.each do |table_name|
dir = case Rails.env
when 'development', 'staging'
'development'
when 'production'
'production'
end
path = Rails.root.join('db', 'seeds', dir, "#{table_name}.rb")
if File.exist?(path)
puts "Creating #{table_name}..."
require(path)
end
end
その下にannouncements.rbを作成
# coding: utf-8
5.times do |n|
Announcement.create(
:subject => "第#{n+1}回赤坂リーグに参加しました!!",
:content => "これは説明です" * 25
)
end
モデルを変更します。
5.times do |n|
Announcement.create(
:subject => "第#{n+1}回赤坂リーグに参加しました!!",
:content => "これは説明です" * 25
)
end
class Announcement < ActiveRecord::Base
validates :subject, :content, :presence => true
validates :subject, :uniqueness => true
validates :content, :length => { :maximum => 2000 }
attr_accessible :content, :subject
end
attr_accessibleを入れないとvalidates :subject, :content, :presence => true
validates :subject, :uniqueness => true
validates :content, :length => { :maximum => 2000 }
attr_accessible :content, :subject
end
rake aborted!
Can't mass-assign protected attributes: subject, content
となるので付けます。
ルーティングの設定をします。同じ名前で書きたいので「namespace」で分けます。
Can't mass-assign protected attributes: subject, content
namespace :api do
resources :announcements, :only => [ :index ]
end
次にapi/announcements_controller.rbを作成します。
resources :announcements, :only => [ :index ]
end
class Api::AnnouncementsController < ApplicationController
respond_to :xml, :json
def index
respond_with(
Announcement.order("created_at DESC"),
:only => [ :id, :subject, :content ],
:skip_types => true
)
end
end
以上でlocalhost:3000/api/announcements.jsonもしくはxmlで表示されます。
respond_to :xml, :json
def index
respond_with(
Announcement.order("created_at DESC"),
:only => [ :id, :subject, :content ],
:skip_types => true
)
end
end
0 件のコメント:
コメントを投稿