Search code examples
ruby-on-railsrubyruby-on-rails-3associationsmodels

Understanding associations in rails 3


Seems I need to brush up on my associations in rails. At present I am trying to display all posts that have the department name as staff.

two models exist at present, posts and departments

class Post < ActiveRecord::Base
  belongs_to :department
  attr_accessible :title, :comments, :department_id
end

class Department < ActiveRecord::Base
  has_many :posts
  attr_accessible :name, :post_id
  #Scopes
  scope :staff_posts, where(:name => "Staff") 
end

So i want to display all posts that have the department name staff

to do this i have put this in my controller

class PublicPagesController < ApplicationController

  def staffnews
    @staffpost = Department.staff_posts
  end

end

In my view i am trying to display all these posts like so

<% @staffpost.each do |t| %>
  <h2><%= t.title %>
  <h2><%= t.comments %></h2>
<% end %>

Clearly going wrong somewhere as i get undefined method nil, even though i have 3 posts with the name 'Staff'

Can someone please explain where i am misunderstanding the association as would love to get this right

EDIT

Routes

scope :controller => :public_pages do 
get "our_news"

match "our_news/staffnews" => "public_pages#staffnews"

Solution

  • In controller it returns department with name staff. And you are using title and comments on on department objects thats why its giving nil method error.

    Use like this:

     def staffnews
       @dept_staff = Department.staff_posts
     end
    
     <% @dept_staff.each do |ds| %>
       <% ds.posts.each do |p| %>
         <h2><%= p.title %></h2>
         <h2><%= p.comments %></h2>
       <% end %>
     <% end %>
    

    or

    In post model create named_scope

    class Post < ActiveRecord::Base
      belongs_to :department
      attr_accessible :title, :comments, :department_id
      scope :staff_posts, :include => :department, :conditions => {"departments.name" => "Staff"}
    end
    
    
    class Department < ActiveRecord::Base
      has_many :posts
      attr_accessible :name, :post_id
    end
    

    Controller:

    def staffnews
      @staffpost = Post.staff_posts
    end
    

    View: #No change

    <% @staffpost.each do |t| %>
      <h2><%= t.title %></h2>
      <h2><%= t.comments %></h2>
    <% end %>