Here are some notes on how to create a has_many relationship and the corresponding APIs for each entity.
> rails new hasMany
> rails g scaffold User name:string
> rails g scaffold Micropost content:string user_id:integer
user.rb
class User < ActiveRecord::Base has_many :microposts, dependent: :destroy end
micropost.rb
class Micropost < ActiveRecord::Base belongs_to :user end
Sample calls
> micropost.user
> user.microposts
> user.microposts.create(arg)
> user.microposts.build
> @micropost = user.microposts.build(content: “Lorem ipsum”)
Links that help
http://ruby.railstutorial.org/book/ruby-on-rails-tutorial#sec-demo_user_has_many_microposts
Leave a Reply