lundi 19 septembre 2016

Rails 5: Refactoring - One to Many Relationship (Tests and Views)

Somewhat new to rails and trying to figure out some answers to questions I've been having with no real luck using the Rails Documentation or on the rails guides, or rails tutorials.

My goal is to embrace how rails handles things and try to make it easy for other developers to step into the project later.

Question 1: Refactoring Question

Rails practice in refactoring. I'm not sure if this should go in the model or the controller and really just want to know what items should go in the controller versus what should go in the model.

First Iteration :

<% @departments.each do |department| %>
      <tr>
        <td><%= department.name %></td>
        <td><%= department.description %></td>
        <td>
          <%= library = Library.find_by(id: department.library_id).name %>
        </td>
        <td><%= link_to 'Show', department %></td>
        <td><%= link_to 'Edit', edit_department_path(department) %></td>
        <td><%= link_to 'Destroy', department, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>

This seemed wrong to me and seemed like that should be taken out of that part as backend logic.

Second Iteration:

Model

class Department < ApplicationRecord
  belongs_to :library

  def get_library_name(lib_id)
    library = Library.find_by(id: lib_id)
    return library.name
  end
end

View

<% @departments.each do |department| %>
      <tr>
        <td><%= department.name %></td>
        <td><%= department.description %></td>
        <td>
          <%= department.get_library_name(department.library_id) %>
        </td>
        <td><%= link_to 'Show', department %></td>
        <td><%= link_to 'Edit', edit_department_path(department) %></td>
        <td><%= link_to 'Destroy', department, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>

This feels more correct, but not all the way there, so I'm not really sure how I can change it to be more correct, especially since the index view which lists out the records is very similar.

How should I refactor this?

Question 2: My Test Won't Pass

Either way, my test isn't passing. I'm guessing it is the way I'm using my one to many relationships.

  test "should get index" do
    get departments_url
    assert_response :success
  end

error:

DepartmentsControllerTest#test_should_get_index:
ActionView::Template::Error: undefined method `name' for nil:NilClass
    app/models/department.rb:6:in `get_library_name'
    app/views/admin/departments/index.html.erb:21:in `block in _app_views_admin_departments_index_html_erb__1894713831414342893_57284960'
    app/views/admin/departments/index.html.erb:16:in `_app_views_admin_departments_index_html_erb__1894713831414342893_57284960'
    test/controllers/departments_controller_test.rb:11:in `block in <class:DepartmentsControllerTest>'

Aucun commentaire:

Enregistrer un commentaire