Skip to content

Associations

JP Barbosa edited this page Jan 14, 2016 · 6 revisions

Associations

Generate basic CRUD for authors
rails g scaffold Author name:string email:string --no-helper --no-assets
Generate association between articles and authors
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
Add author_id to trusted parameters
nano app/controllers/articles_controller.rb
...
    def article_params
      params.require(:article).permit(:title, :content, :author_id)
    end
...
Create author using cURL
curl -H "Accept: application/json" \
     http://localhost:3000/authors \
     --data "author[name]=Author Name" \
     --data "author[email][email protected]"
Open author in the browser and check if the new record was created
open http://localhost:3000/authors
Associate author to existing article using cURL
curl -H "Accept: application/json" \
     http://localhost:3000/articles/1.json \
     --data "_method=patch" \
     --data "article[author_id]=1"
Add author to articles views HTML
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>
...
Add author to articles views JSON
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 articles in the browser and check if there are records with authors
open http://localhost:3000/articles
Add authors and associations to Git
git add .
git commit -m "Add authors and associations"
Next step: SimpleForm