Skip to content

Instantly share code, notes, and snippets.

@ttanimichi
Created January 8, 2014 09:40
Show Gist options
  • Save ttanimichi/8314182 to your computer and use it in GitHub Desktop.
Save ttanimichi/8314182 to your computer and use it in GitHub Desktop.
ActiveRecordを単体で使い1対多の関連を持つ2つのテーブルを作成するサンプルコード
# -*- coding: utf-8 -*-
require 'active_record'
ActiveRecord::Base.establish_connection(
"adapter" => "sqlite3",
"database" => "./sample.sqlite")
class CreateWebSite < ActiveRecord::Migration
def up
create_table :web_sites do |t|
t.string :name
t.string :url
t.timestamps
end
end
end
class CreateBlogArticle < ActiveRecord::Migration
def up
create_table :blog_articles do |t|
t.integer :web_site_id
t.string :title
t.string :link
t.timestamps
end
end
end
class WebSite < ActiveRecord::Base
has_many :blog_articles
end
class BlogArticle < ActiveRecord::Base
belongs_to :web_site
end
CreateWebSite.new.up
CreateBlogArticle.new.up
w = WebSite.new(:name => "tkr's blog", :url => "http://tkr.hatenablog.com/")
a1 = BlogArticle.new(
:title => "Underscore.jsを再開発する",
:link => "http://tkr.hatenablog.com/entry/2013/10/20/200734")
a2 = BlogArticle.new(
:title => "bundlerの使い方とGemfileの書き方について",
:link => "http://tkr.hatenablog.com/entry/2013/09/28/172105")
a3 = BlogArticle.new(
:title => "ダミーテキストを生成するgemを作った",
:link => "http://d.hatena.ne.jp/kasei_san/20120402/p1")
a1.web_site = w; a1.save
a2.web_site = w; a2.save
a3.web_site = w; a3.save
w.save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment