0

看来我需要重温一下我在 Rails 中的联想。目前我正在尝试显示所有以部门名称为员工的帖子。

目前有两种模式,岗位和部门

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

所以我想显示所有具有部门名称人员的帖子

为此,我已将其放入我的控制器中

class PublicPagesController < ApplicationController

  def staffnews
    @staffpost = Department.staff_posts
  end

end

在我看来,我正试图像这样显示所有这些帖子

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

当我得到未定义的方法 nil 时,显然某处出错了,即使我有 3 个名为“员工”的帖子

有人可以解释一下我在哪里误解了协会,因为我很想把这个做对

编辑

路线

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

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

3 回答 3

4

在控制器中,它返回带有名称员工的部门。而且您正在对部门对象使用标题和评论,这就是它给出 nil 方法错误的原因。

像这样使用:

 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 %>

或者

在后期模型创建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

控制器:

def staffnews
  @staffpost = Post.staff_posts
end

查看:#无变化

<% @staffpost.each do |t| %>
  <h2><%= t.title %></h2>
  <h2><%= t.comments %></h2>
<% end %>
于 2013-02-01T19:52:24.880 回答
0

您的staff_posts范围仅选择名称为“员工”的部门。假设您将有一个且只有一个名为员工的部门,您有几种方法来处理这个问题。

这将找到所有名称为员工的部门,并急切地加载与之相关的帖子:

@department = Department.where(name: "Staff").include(:posts).first

但是,由于您正在尝试确定 Post 的范围,因此它属于 Post。这是一个使用方法作为范围的示例:

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

  def self.staff
    where(department_id: staff_department_id)
  end

  def staff_department_id
    Department.find_by_name!("Staff").id
  end

end

这样,您可以使用@staff_posts = Post.staff和迭代该集合(注意:我不建议staff_department_id永久使用这种方式。可以在应用程序启动时将其设置为常量,或其他更强大的解决方案)。

于 2013-02-01T19:56:07.943 回答
0

您可以通过以下更改找到所有具有部门名称人员的帖子:

类 PublicPagesController < ApplicationController

def staffnews
    #get all the department which have name is staff
    departments = Department.where("name=?","staff")

    #get all the ids
    department_ids = departments.map(&:id)

    #retrieve post that department name is staff 
    @staffpost = Post.find_by_department_id(department_ids)
end

结尾

于 2013-02-01T20:25:02.857 回答