前回のGroupにUserが属している内容を表示させる。
$ rails g controller users index
create app/controllers/users_controller.rb
route get "users/index"
invoke erb
create app/views/users
create app/views/users/index.html.erb
invoke test_unit
create test/functional/users_controller_test.rb
invoke helper
create app/helpers/users_helper.rb
invoke test_unit
create test/unit/helpers/users_helper_test.rb
invoke assets
invoke coffee
create app/assets/javascripts/users.js.coffee
invoke scss
create app/assets/stylesheets/users.css.scss
モデルも一緒に作ります。
$ rails g model user
invoke active_record
create db/migrate/20120427062021_create_users.rb
create app/models/user.rb
invoke test_unit
create test/unit/user_test.rb
create test/fixtures/users.yml
model/user.rbを変更します。
class User < ActiveRecord::Base
belongs_to :groups
validates :name, :presence => true
attr_accessible :name, :email, :email,
:sex, :country, :area, :address1,
:address2, :phone, :hits, :catches, :balls, :group
end
model/group.rbに追加
has_many :users, :dependent => :destroy
マイグレーションを作成
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.references :group, :null => false
t.string :name
t.string :email
t.string :sex
t.string :country
t.string :area
t.string :address1
t.string :address2
t.string :phone
t.text :hits
t.text :catches
t.text :balls
t.timestamps
end
add_index :users, :group_id
end
end
じゃあ入れましょう。
$ rake db:migrate
development/groups.rbに追加
# coding: utf-8
group = Group.create!(
:name => "グループ1"
)
hits = [ 100, 200, 300 ]
catches = [ 10, 20, 30, 40, 50, 60 ]
balls = [
{ :change => 1, :level => 10 },
{ :change => 2, :level => 20 },
{ :change => 3, :level => 30 },
{ :change => 4, :level => 40 },
{ :change => 5, :level => 50 },
]
10.times do |n|
User.create!(
:name => "名前#{n}",
:sex => "男",
:country => "東京",
:area => "港区",
:address1 => "芝大門",
:address2 => "1-1-1-101",
:phone => "03-1234-5678",
:hits => hits,
:catches => catches,
:balls => balls,
:group => group
)
end
api/groups_controller.rbに追加します
def show
@group = Group.find(params[:id])
respond_to do |format|
format.xml do
render :xml => @group.to_xml(
:only => [ :id, :name ],
:skip_types => true,
:include => [ :users ]
)
end
format.json { render:json => @group.as_json_with_image }
end
end
モデルで表示する
user.rbを編集
def to_xml(options = {})
options[:indent] ||= 2
xml = options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent])
xml.user do
xml.id id
xml.name name
xml.sex sex
xml.country country
xml.area area
xml.address1 address1
xml.address2 address2
xml.phone phone
end
end
end
モデルを編集
group.rb
def as_json_with_image
{
:users => users.map { |u|
{
:id => u.id,
:name => u.name,
:sex => u.sex,
:country => u.country,
:area => u.area,
:address1 => u.address1,
:address2 => u.address2,
:phone => u.phone
}
}
}
end
ここまでで配列以外を表示することが出来ました。