【问题标题】:Instance variable in partial view局部视图中的实例变量
【发布时间】:2015-06-10 21:11:12
【问题描述】:

我有一个导航栏,它是我需要在设计页面上呈现的部分视图,以便用户编辑他们的个人资料。实际上,我只有一页,但是添加执行帐户维护的路径会因为实例变量不存在而弄乱了我的导航栏加载。无论如何,我怎样才能获得一个全局实例变量,它适用于我的导航栏?

application_helper.rb

def get_company
  @company = current_user.company
end

def get_locations(company)
  @locations = if @company
    current_user.company_locations.order(:name)
  else
    []
  end
end

pages_controller.rb

def home
  @company = get_company
  @locations = get_locations(@company)
  @reports = if @company
    @company.reports.order("created_at DESC").limit(5)
  else
    []
  end
end

views/devise/registrations/edit.html.erb

<%= render partial: "pages/navigation" %>
... devise form ....

pages/_navigation.html.erb

<li class="right-menu-item">
      <button class="btn dropdown-toggle " type="button" id="dropdownMenu1" data-toggle="dropdown">
        <% if @company %>
          <%= @company.name %>
        <% else %>
          <%= current_user.email %>
        <% end %>
        <span class="caret"></span>
      </button>
      <ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dropdownMenu1">
        <% @locations.each do |location| %>
          <li role="presentation">
            <%= link_to root_path(location_id: location.id), role: "menuitem", tabindex: "-1" do %>
              <%= image_tag "check-green.svg" if location == @location %>
              <span><%= location.name %></span>
            <% end %>
          </li>
        <% end %>
      </ul>

问题出在哪里:

我在这里缺少什么以使此功能适用于所有视图?

谢谢!

【问题讨论】:

  • get_company 不接受参数时,您正在调用它。你确定这是正确的代码吗?我所看到的只是您的home 操作的代码,而edit 什么也没有。
  • 对不起@tadman 你是对的。当我发布这个时,我确实从传递 pages_controller 中取出了 current_user 参数。我现在在手机上,否则我会编辑。现在是“@company = get_company”
  • 编辑 pages_controller
  • 仍然很确定没有代码在运行,因为控制器中的操作与视图名称不匹配。
  • 我认为这是我的问题,因此是问题所在。设计视图位于 pages_controller 之外,这就是为什么“@locations”在渲染部分视图后会在部分视图中解决问题。无论我在什么视图中并且正在调用控制器,有没有办法让实例变量可以全面访问?

标签: css ruby-on-rails ruby twitter-bootstrap devise


【解决方案1】:

好的,看来Where is the controller of Devise ? how to add data from other models in users/edit page? 很有帮助。我必须执行以下操作才能在部分设计视图中完成这项工作:

rails g devise:controllers users -c registrations

controllers/users/registrations.rb 下创建了一个注册控制器,然后我可以添加我需要的实例变量来执行 edit 方法:

def edit
  @company = get_company
  @locations = get_locations(@company)
end

还必须稍微更改 route.rb 文件以方便新控制器:

devise_for :users, skip: [:sessions],
                   controllers: {
                     registrations: 'users/registrations'
                   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多