【发布时间】:2013-02-01 19:42:23
【问题描述】:
看来我需要重温一下我在 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"
【问题讨论】:
-
“看来我需要重新认识我的联想”——我为此推荐一本书。结构化知识比 SO 帖子更有用。
-
在控制器中,它返回带有名称员工的部门。你在部门对象上使用 title 和 cmets 这就是为什么没有方法错误发生
-
@SergioTulentsev 除了常规 Rails 文档之外的任何建议,即您是否遇到过简化解释的博客或帖子
-
我不确定,我现在无法测试它,因为我远离我的笔记本电脑。但据我所知,您已经在部门模型中声明了范围,
Department.staff_posts将返回名称为“员工”的部门。我不确定,但@staffposts = Department.staff_posts.first.posts应该获取帖子。如果这不起作用,那么您可以使用@staffposts = Department.find_by_name('staff').posts。
标签: ruby-on-rails ruby ruby-on-rails-3 associations models