Skip to content

Instantly share code, notes, and snippets.

@jblac
Last active December 13, 2015 22:08
Show Gist options
  • Save jblac/4981855 to your computer and use it in GitHub Desktop.
Save jblac/4981855 to your computer and use it in GitHub Desktop.
user.company fails to load anything...
class Company < ActiveRecord::Base
attr_accessible :address, :city, :contact_email, :contact_name, :fax_number, :name, :phone_number, :state, :zip
has_many :users
end
class User < ActiveRecord::Base
attr_accessible :company_id, :email, :enabled, :first_name, :last_name, :password, :username
belongs_to :company
end
class UsersController < ApplicationController
# GET /users
# GET /users.json
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
end
<% @users.each do |user| %>
<tr>
<td><%= user.username %></td>
<td><%= user.email %></td>
<td><%= user.first_name %></td>
<td><%= user.last_name %></td>
<td><%= user.company %></td>
<td><%= user.enabled %></td>
<td><%= link_to 'Show', user %></td>
<td><%= link_to 'Edit', edit_user_path(user) %></td>
<td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
class CreateCompanies < ActiveRecord::Migration
def change
create_table :companies do |t|
t.string :name
t.string :phone_number
t.string :fax_number
t.string :address
t.string :city
t.string :state
t.string :zip
t.string :contact_name
t.string :contact_email
t.timestamps
end
end
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :first_name
t.string :last_name
t.integer :company_id
t.string :password
t.integer :enabled
t.timestamps
end
end
end
@raul-gracia
Copy link

You need to access to an attribute of the company class:

 <td><%= user.company.name %></td>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment