Web Programming examples

Google Maps,AngularJS

Archives

Ruby on Rails Tutorial micropost model,associations

(1)micropost model

1.basic model

$ rails generate model Micropost content:string user_id:integer

2.add index

$ vi db/migrate/…._create_microposts.rb

class CreateMicroposts < ActiveRecord::Migration
  def change
    create_table :microposts do |t|
      t.string :content
      t.integer :user_id

      t.timestamps
    end
    add_index :microposts, [:user_id, :created_at]
  end
end

3.migrate

$ bundle exec rake db:migrate

4.micropost validations

$ vi app/models/micropost.rb

class Micropost < ActiveRecord::Base
  validates :content, presence: true, length: { maximum: 140 }
  validates :user_id, presence: true
end

(2)User/Micropost associations

1. Micropost model

$ vi app/models/micropost.rb

class Micropost < ActiveRecord::Base
  belongs_to :user
......

2. User model

$ vi app/models/user.rb

class User < ActiveRecord::Base
  has_many :microposts, dependent: :destroy
.....

3. check

$ rails console

2.0.0p247 :001 > micropost = Micropost.create(content: "Test #1", user_id: 10)

2.0.0p247 :002 > micropost = Micropost.create(content: "Test #2", user_id: 10)

2.0.0p247 :003 > micropost=Micropost.find_by(user_id: 10)
  Micropost Load (0.3ms)  SELECT  "microposts".* FROM "microposts"  WHERE "microposts"."user_id" = 10 LIMIT 1
 => #<Micropost id: 1, content: "Test #1", user_id: 10, created_at: "2015-07-21 00:00:50", updated_at: "2015-07-21 00:00:50">

2.0.0p247 :004 > micropost.user
  User Load (0.1ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = ? LIMIT 1  [["id", 10]]
 => #<User id: 10, name: "testuser10", email: "test10@example.com", created_at: "2015-07-13 08:45:35", updated_at: "2015-07-20 08:30:47", password_digest: "$2a$10$BLM/nUrE1wptItRDOkKm4OynNZ718yjoDnnIBUkWL0s…", remember_token: "48c3edd244e42156c38e89fca5fe5616c5cfcce1", admin: false>