Reputation: 167
I'm writing a simple time tracking app where the user has_many clients and where the client has_many projects.
I want a user to be able to view a list of their projects (for all clients). To implement this, I've set up a has_many, through relationship between the users and projects.
But for some reason I can't get the projects to show up in their index view. There's probably a really simple reason for this that I'm just not noticing, so apologies upfront if that's the case.
Here's the relevant code.
Project index controller:
def index
@projects = current_user.projects.paginate(:page => params[:page], :per_page => 6)
end
Project model:
class Project < ActiveRecord::Base
belongs_to :client
validates :name, presence: true, length: { maximum: 30 }
validates :fee, presence: true, numericality: { only_integer: true,
greater_than_or_equal_to: 0, less_than_or_equal_to: 100000 }
validates :client_id, presence: true
end
Client model:
class Client < ActiveRecord::Base
belongs_to :user
has_many :projects, dependent: :destroy
validates :user_id, presence: true
validates :name, presence: true, length: { maximum: 30 }
validate :user_id_is_valid
private
def user_id_is_valid
errors.add(:user_id, "is invalid") unless User.exists?(self.user_id)
end
end
Relevant part of the User model:
class User < ActiveRecord::Base
has_many :clients, dependent: :destroy
has_many :projects, through: :clients
index.html.erb:
<div id="projects-list">
<% if current_user.projects.any? %>
<h3>Projects</h3>
<ul class="project-list">
<% render @projects %>
</ul>
<%= will_paginate @projects %>
<% end %>
</div>
_project.html.erb:
<li>
<%= link_to "#{project.name}", '#' %>
</li>
Upvotes: 0
Views: 367
Reputation: 44675
It should be:
<%= render @projects %>
Not:
<% render @projects %>
Upvotes: 1