如果没有发送params[:subject_id]
,如何显示表格中的所有记录,或者如果发送params[:subject_id]
,则如何过滤显示的记录?
到目前为止,我在页面控制器中有一个前置过滤器,用于检查params[:subject_id]
是否已发送并创建实例变量。
private
def find_subject
if params[:subject_id]
@subject = Subject.find_by_id(params[:subject_id])
else
@subject = Subject.all
end
end
问题出现在这样的动作中,像这样@pages
只存储最后一条记录,但不会破坏视图中的任何内容。
before_filter :find_subject
def list
@subject.each do |subject|
@pages = Page.order("pages.position ASC").where(:subject_id => subject.id)
end
end
但是,如果我这样做
def list
@pages = Page.order("pages.position ASC").where(:subject_id => @subject.id)
end
根本没有返回返回的记录,当我在webrick控制台中检查输出时我看到了这个
Subject Load (0.2ms) SELECT `subjects`.* FROM `subjects`
Page Load (0.4ms) SELECT `pages`.* FROM `pages` WHERE `pages`.`subject_id` = 2186859380 ORDER BY pages.position ASC
我不确定它是如何获得2186859380
我也这样累了
def list
if @subject.object_id.nil?
@pages = Page.order("pages.position ASC")
else
@pages = Page.order("pages.position ASC").where(:subject_id => @subject.object_id)
end
end
然而,这也会引发一些错误并打破我的观点。
这是我的观点,所以你可以得到一个完整的图片
<div class="page list">
<h2>Pages</h2>
<%= link_to "Add a new Page", {:action => "new", :subject_id => @subject.id}, :class => "action new" %>
<table class="listing" summary="Pages List">
<tr class="header">
<th> </th>
<th>Subject</th>
<th>Page</th>
<th>Visible</th>
<th>Sections</th>
<th>Permalink</th>
<th>Actions</th>
</tr>
<% @pages.each do |page| %>
<tr class="<%= cycle("odd", "even") %>">
<td><%= page.position %></td>
<td><%= page.subject.name %></td>
<td><%= page.name %></td>
<td class="center"><%= page.visible ? "Yes" : "No" %></td>
<td class="center"><%= page.sections.size %></td>
<td><%= page.permalink %></td>
<td class="actions">
<%= link_to("Sections", {:controller => "sections", :action => "list", :page_id => page.id}, :class => "action delete")%>
<%= link_to("Show", {:action => "show", :id => page.id, :subject_id => @subject.id}, :class => "action show")%>
<%= link_to("Edit", {:action => "edit", :id => page.id, :subject_id => @subject.id}, :class => "action edit")%>
<%= link_to("Delete", {:action => "delete", :id => page.id, :subject_id => @subject.id}, :class => "action delete")%>
</td>
</tr>
<% end %>
</table>
</div>
对我所做错的任何帮助都将不胜感激。
答案 0 :(得分:1)
我认为你应该像这里一样添加一个“s”:
private
def find_subject
if params[:subject_id]
@subject = Subject.find_by_id(params[:subject_id])
else
@subjects = Subject.all
end
end
现在,您可以这样做:
def list
if subjects
@subject.each do |subject|
@pages = Page.order("pages.position ASC").where(:subject_id => subject.id)
end
else
@pages = Page.order("pages.position ASC").where(:subject_id => @subject.id)
end
end
你可以在你看来做类似的事情......