2015-12-18 21 views
0

我的應用程序有一個服務器和域模塊,例如服務器has_many域和域belongs_to服務器。rails部分未收到變量

我試圖渲染服務器控制器部分:

def get_domain_checkboxes 
     @domains = Domain.find_by(:server_id => params[:id]) 
     render :partial => 'servers/domain_checkboxes', :layout => nil 
    end 

局部「_domain_checkboxes.html.erb」載:

<% @domains.each do |domain| %> 
    domain.url 
<% end %> 

但是要當我得到一個錯誤'servers/3/get_domain_checkboxes'路線和跟蹤說:

Started GET "/servers/3/get_domain_checkboxes" for ::1 at 2015-12-18 05:03:08 +0200 
Processing by ServersController#get_domain_checkboxes as HTML 
    Parameters: {"server_id"=>"3"} 
    Domain Load (0.3ms) SELECT "domains".* FROM "domains" WHERE "domains"."server_id" IS NULL LIMIT 1 
    Rendered servers/_domain_checkboxes.html.erb (1.4ms) 
Completed 500 Internal Server Error in 9ms (ActiveRecord: 0.4ms) 

ActionView::Template::Error (undefined method `each' for nil:NilClass): 
    1: <% @domains.each do |domain| %> 
    2:  hello 
    3: <% end %> 
    app/views/servers/_domain_checkboxes.html.erb:1:in `_app_views_servers__domain_checkboxes_html_erb___2806237560631891313_70206341448100' 
    app/controllers/servers_controller.rb:71:in `get_domain_checkboxes' 

嘗試過去一小時。可能是我錯過的簡單東西?

編輯:

嘗試@domains = Domain.find_by(:server_id => params[:server_id])代替,但仍得到一個錯誤:

Started GET "/servers/3/get_domain_checkboxes" for ::1 at 2015-12-18 05:09:43 +0200 
Processing by ServersController#get_domain_checkboxes as HTML 
    Parameters: {"server_id"=>"3"} 
    Domain Load (0.1ms) SELECT "domains".* FROM "domains" WHERE "domains"."server_id" = ? LIMIT 1 [["server_id", 3]] 
    Rendered servers/_domain_checkboxes.html.erb (1.6ms) 
Completed 500 Internal Server Error in 3ms (ActiveRecord: 0.1ms) 

ActionView::Template::Error (undefined method `each' for #<Domain:0x007fb465810738>): 
    1: <% @domains.each do |domain| %> 
    2:  hello 
    3: <% end %> 
    app/views/servers/_domain_checkboxes.html.erb:1:in `_app_views_servers__domain_checkboxes_html_erb___2806237560631891313_70206341448100' 
    app/controllers/servers_controller.rb:71:in `get_domain_checkboxes' 

回答

3

你需要改變:

@domains = Domain.find_by(:server_id => params[:id]) 

@domains = Domain.where(:server_id => params[:server_id]) 
+0

仍然出現錯誤,雖然有點不同。查看編輯問題 – Tom

+0

@Tom - 更新了答案。 – BroiSatse

+0

工作!那爲什麼呢? – Tom