【发布时间】:2011-09-20 01:07:19
【问题描述】:
我对 Rails 很陌生,有一个相当基本的问题:
我有一个接受数组的表单:
<td><%= fields_for "days" do |form| %>
M: <%= form.check_box "", {}, 'M', '' %>
T: <%= form.check_box "", {}, 'T', '' %>
W: <%= form.check_box "", {}, 'W', '' %>
Th: <%= form.check_box "", {}, 'Th', '' %>
F: <%= form.check_box "", {}, 'F', '' %>
<% end %>
这应该可以通过 params[:days] 访问。如何将 params[:days] 分配给控制器中的变量? @days 在这里不正确,对吧? (没有 Days 对象,因此没有该对象的实例)。下面的 [correct_variable] 槽应该放什么?
[correct_variable] = params[:days]
谢谢!
回应cmets:
我尝试使用@days,但由于某种原因,它不会在我想要的地方被调用。特别是,我想将它传递给我的搜索模型:
class Search < ActiveRecord::Base
attr_accessible :name, :day, :units, :instructor
def courses
@courses ||= find_courses
end
private
def find_courses
Course.find(:all, :conditions => conditions)
end
def day_conditions
["courses.day LIKE ?", "%"+ @days.join("%")+"%"]
end
我首先在我的课程控制器中实例化@days(通过 index 方法连接到使用 Search 对象实例的部分。
更多代码:
来自课程/index.html.erb:
<% if @search.save %>
<div id = "results_scroll">
<%= render :partial => 'searches/search_results' %>
</div>
<% else %>
来自 search_results 部分:
<% "Search" %>
<table>
<tr>
<th align="left" width="25%"><%= 'Name' %></th>
<th align="left" width="10%"><%= 'Number' %></th>
<th align="left" width="20%"><%= 'Instructor' %></th>
<th align="left" width="10%"><%= 'Room' %></th>
<th align="left" width="5%"><%= 'Day' %></th>
<th align="left" width="5%"><%= 'Units' %></th>
<th align="left" width="15%"><%= 'Time' %></th>
<th align="left" width="10%"><%= 'Limitations' %></th>
</tr>
<%= render :partial => @search_show.courses %>
</table>
来自课程控制器(这有 @search_show 变量)。
def index
@courses = Course.order(sort_column + " " + sort_direction)
@search = Search.new
@search_show = Search.last
@title = "List"
@days = params[:days]
最后是 _course.html.erb 部分:
<tr>
<td><%= course.name %></td>
<td><%= course.number %></td>
<td><%= course.instructor %></td>
<td><%= course.room %></td>
<td><%= course.day %></td>
<td><%= course.units %></td>
<td><%= course.time %></td>
<td><%= course.limitations %></td>
<td><%= link_to 'Show', course %></td>
</tr>
【问题讨论】:
-
我不是 100% 了解您的要求。
@days = params[:days]有什么问题?您说没有“Days 对象”,但这不是预期值吗?如果没有@days,那么您将不会覆盖某些内容 -
对我的问题添加了一些评论。希望对您有所帮助。
-
这是在课程控制器中吗?你在哪里打部分电话?在课程/index.html.erb 内?你要路由到哪里? “课程#index”?
-
这实际上来自我的搜索模型。在我的课程/index.html.erb 中,我调用了“搜索结果”部分,它调用了 @search_show.courses 部分。 [at]search_show 是我在 Courses 控制器的 index 方法下的一个变量,它调用最后一次搜索。我知道这很多,所以我会尝试在我的问题中添加更多内容。感谢您的所有帮助!
标签: ruby-on-rails controller params