我有一个菜单控制器,它在 routes.rb 中设置为我的根控制器。在我的菜单视图中,我尝试渲染 _lights.slim 部分,= render :partial => 'lights/lights'
但出现以下错误:undefined method `lights' for nil:NilClass
菜单控制器:
class MenuController < ApplicationController
def index
end
end
菜单视图(index.slim)
ul.tabs.vertical data-tab=""
li.tab-title.active
a href="#panel1a" Tab 1
.tabs-content.vertical
#panel1a.content.active
= render :partial => 'lights/lights'
灯光控制器
class LightsController < ApplicationController
before_action :discover_lights
include LIFX
@client = LIFX::Client.lan
@client.discover!
3.times do
@client.lights.refresh
sleep (0.5)
puts "Found #{@client.lights.count} with labels #{@client.lights}"
end
def index
end
def new
end
def light_toggle
light = @client.lights.with_label(params[:label])
light.on? ? light.turn_off : light.turn_on
redirect_to '/'
end
private
def discover_lights
@client = LIFX::Client.lan
@client.discover!
end
end
灯光视图(_lights.slim)
h1.subheader LIFX Lights
table.light-table
thead
tr
th Light
th Status
th Power On/Off
th Brightness
tbody
-@client.lights.map do |c|
tr
th #{c.label}
th #{c.power}
th =link_to 'Toggle', light_path(:label => c.label)
th #{c.color.brightness.round(2) * 100}%
end
路由.rb
root 'menu#index'
get '/lights', to: 'lights#index'
get '/lights/:label', to: 'lights#light_toggle', as: 'light'
我知道这很简单,但我不知道在这里做什么。我认为这一定是一个问题,当Menu#Index
被调用时,我永远不知道 my LightsController
,所以@client.blablabla 永远不会有意义。LightsController
但是当视图作为部分加载时,我将如何让我的应用程序知道我的