需求:想实现通过 view 传递搜索关键字到 controller,进行变量 select,最终改变变量反馈到 view。各位大神有啥好方法。
ruby
<%= form_tag("/search", method: :get) do %>
<%= text_field_tag :search, params[:search], class: 'form-control search', placeholder: "search..." %>
<% end %>
ruby
def search
@cm = @cma.select { |k,j| k =~/#{params[:search]}/ }
render "index"
end
def index
@cma = list.select {|k,j| k =~/cm/ }
.......
end
undefined method `each' for nil:NilClass
#1 楼 @ywjno 依旧是 undefined method `each' for nil:NilClass
Started GET "/search?utf8=%E2%9C%93&search=s" for 192.168.8.166 at 2016-01-04 14:09:40 +0000
Processing by HomesController#search as HTML
Parameters: {"utf8"=>"✓", "search"=>"s"}
Rendered homes/index.html.erb within layouts/application (269.6ms)
Completed 500 Internal Server Error in 312ms
ActionView::Template::Error (undefined method `each' for nil:NilClass):
#4 楼 @qinfanpeng 我有点小白,有个疑问同样的 controller 在 index 传递到 view 中是正常,但在方法 search 中却 nil……
首先我很好奇这个 search 的 form 写在了哪个 view 里面,在你访问
search?utf8=%E2%9C%93&search=s
的时候@cma和 list 是否已经赋值了。单凭眼睛看而缺少上下文的环境下,我也很难指出哪里出了问题,建议加个 binding.pry 调试一下。
#6 楼 @nowherekai #7 楼 @qinfanpeng
ruby
match '/search', to: 'homes#search', via: :get
def index url = Docker::Container.all({}, Docker::Connection.new('tcp://192.168.1.10:2375', {})) list = url.collect { |url| [url.info["Image"], url.info["Ports"][0]["PublicPort"]]} @dsa = list.select {|k,j| k =~/ds/ } @ds = @dsa.each {|k| k[1]=k[1]/100} end end
- view代码如下
```ruby
<%= form_tag("/search", method: :get) do %>
<%= text_field_tag :search, params[:search], class: 'form-control search', placeholder: "search..." %>
<% end %>
<% @ds.each do |p, k| %>
ActionView::Template::Error (undefined method `each' for nil:NilClass): 62: <% end %> 63: 64: 65: <% @ds.each do |p, k| %>
@ds = @dsa.select { |k,j| k =~/#{params[:search]}/ }
这里加个空值保护啊,万一你的检索条件是一个值也没有检索出来的,@ds就是 nil 不能用 each 方法了。
#13 楼 @qinfanpeng #14 楼 @adamshen #6 楼 @nowherekai #1 楼 @ywjno 貌似可以了。。。我先回想,等下写总结,太感谢各位了。