-
Notifications
You must be signed in to change notification settings - Fork 8
Associations
JP Barbosa edited this page Jan 14, 2016
·
6 revisions
rails g scaffold Author name:string email:string --no-helper --no-assets
rails g migration AddAuthorToArticles author:references
nano app/models/article.rb
class Article < ActiveRecord::Base
belongs_to :author
..
nano app/models/author.rb
class Author < ActiveRecord::Base
has_many :articles
...
rake db:migrate
nano app/controllers/articles_controller.rb
...
def article_params
params.require(:article).permit(:title, :content, :author_id)
end
...
curl -H "Accept: application/json" \
http://localhost:3000/authors \
--data "author[name]=Author Name" \
--data "author[email][email protected]"
open http://localhost:3000/authors
curl -H "Accept: application/json" \
http://localhost:3000/articles/1.json \
--data "_method=patch" \
--data "article[author_id]=1"
nano app/views/articles/index.html.erb
...
<th>Title</th>
<th>Content</th>
<th>Author</th>
...
<td><%= article.title %></td>
<td><%= article.content %></td>
<td><%= article.author.name if article.author %></td>
...
nano app/views/articles/_form.html.erb
...
<div class="field">
<%= f.label :author %><br>
<%= f.collection_select(:author_id, Author.all, :id, :name, prompt: 'Select Author') %>
</div>
...
nano app/views/articles/show.html.erb
...
<p>
<strong>Author:</strong>
<%= @article.author.name if @article.author %>
</p>
...
nano app/views/articles/index.json.jbuilder
json.extract! article, :id, :title, :content, :author
nano app/views/articles/show.json.jbuilder
json.extract! @article, :id, :title, :content, :author, :created_at, :updated_at
open http://localhost:3000/articles
git add .
git commit -m "Add authors and associations"