简体   繁体   English

在应用程序html.erb中使用控制器变量

[英]Using a controller variable in application html.erb

I'm probably trying too hard for my first website but i wanted to make a dropdown on a (bootstrap) navbar to be flexible, and show the names of the saved work categories. 我可能对我的第一个网站太努力,但我想在(引导程序)导航栏上下拉灵活,并显示已保存工作类别的名称。

This is what i've tried to do in the application.html.erb file : 这是我在application.html.erb文件中尝试做的事情:

  <ul class="dropdown-menu">
    <% @workcategory.each do |workcategory| %>
    <li><%= workcategory.name%></li>
    <% end %>

Failed with error undefined method each' for nil:NilClass on the <% @workcategory.each do |workcategory| 失败的错误undefined method每个'为nil:NilClass on the <%@ workcategory.each do | workcategory | %>` line. %>`行。

This is the workcategories controller : 这是workcategories控制器:

class WorkcategoriesController < ApplicationController
    before_action :find_workcategory, only: [:edit, :update, :destroy]
    def index
        @workcategories = Workcategory.all.order("created_at DESC")
    end
    def new
        @workcategory = Workcategory.new
    end
    def create
        @workcategory = Workcategory.new(post_params)
        if @workcategory.save
            flash[:notice] = "Workcategory created"
            redirect_to(:action=>'index', :workcategory_id => @workcategory.id)
        else
            @workcategories = Workcategories.order()
            render('new')
        end
    end

    def edit
    end

    def update
    end

    def destroy
        @workcategory.destroy
        redirect_to workcategory_path
    end
    private
    def find_workcategory
        @workcategory=Workcategory.find(params[:id])
    end
    def post_params
        params.require(:workcategory).permit(:name)
    end
end

Any tips and help are welcome, even non-related to the initial question :) Thank you 欢迎任何提示和帮助,甚至与初始问题无关:)谢谢

If you want it in all ur actions, it is wise to put it in your application_controller.rb . 如果你想在所有的操作中使用它,最好将它放在application_controller.rb

before_filter :set_work_categories

def set_work_categoriers
    @w_categories =  Workcategory.all.order("created_at DESC")
end

This should work fine. 这应该工作正常。

Also, a tip. 还有,小费。

You can use default_scope {order(created_at: :desc)} in your model WorkCategory.rb 您可以在模型WorkCategory.rb使用default_scope {order(created_at: :desc)}

Then you can use this like, 那么你可以使用这个,

def set_work_categoriers
  @w_categories =  Workcategory.all
end

I would recommend changing the variable name to @w_categories or else it will conflict with your @work_categories name in index action. 我建议将变量名称更改为@w_categories,否则它将与index操作中的@work_categories名称冲突。

In your application.html.erb file, change application.html.erb文件中,进行更改

<% unless @w_categories.nil? %>
  <ul class="dropdown-menu">
    <% @w_categories.each do |workcategory| %>
      <li><%= workcategory.name%></li>
    <% end %>
  </ul>
<%end>

I guess this should do the trick 我想这应该可以解决问题

If we talk about index action, then you just forgot to use appropriate variable: 如果我们谈论index操作,那么你只是忘了使用适当的变量:

<ul class="dropdown-menu">
  <% @workcategories.each do |workcategory| %>
  <li><%= workcategory.name%></li>
<% end %>

Update 更新

If you want to have this in all actions, then initialize @workcategories in before_action : 如果你想拥有这一切行动,然后初始化@workcategoriesbefore_action

# your_controller.rb
before_action :initialize_work_categories
def initialize_work_categories
  @workcategories = Workcategory.all.order("created_at DESC")
end

Layouts 布局

application.html.erb is a layout , meaning that it will be present regardless of whether you're using the Workcategories controller or not. application.html.erb是一种布局 ,这意味着无论您是否使用Workcategories控制器,它都将存在。

If you want to load a variable into the layout , irrespective of which controller is being invoked, you'll need to make sure the @workcategory variable is present. 如果要将变量加载到布局中 ,无论调用哪个控制器,都需要确保存在@workcategory变量。

To do this, you would generally put the @workcategory declaration into the ApplicationController (which most other controllers inherit from): 为此,您通常会将@workcategory声明放入ApplicationController (大多数其他控制器继承自):

#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
   before_action :set_categories

   private

   def set_categories
      @workcategory = ....
   end
end

This is the standard way to populate layout-side variables. 这是填充布局方变量的标准方法。 It's not efficient and only works if your controllers inherit from the Application controller. 它效率不高, 只有在控制器继承Application控制器时才有效。


Some further pointers would include the following: 一些进一步的指示将包括以下内容:

1. Object orientation 1.面向对象

Ruby, and by virtue, Rails, is object orientated . Ruby,以及Rails,是面向对象的

This means that everything you do should revolve around objects . 这意味着你所做的一切都应围绕对象 This is why Rails has many helpers that seem to work "magically". 这就是为什么Rails有许多帮助者似乎“神奇地”工作的原因。

They're not magic at all - they just take the objects you pass them, and build pre-baked HTML to give you specific functionality. 它们根本不是魔术 - 它们只是接受你传递的对象 ,并构建预先编写的HTML以提供特定的功能。

A good example are the routes : 路线就是一个很好的例子:

#config/routes.rb
resources :controller

在此输入图像描述

The reason this is important is that when you call actions / variables, you need to think of them as objects . 这一点很重要的原因是当你调用actions / variables时,你需要将它们视为对象 This is difficult to do for newbies, but if you can get your head around it, it helps your coding massively. 对于新手来说这很难做到,但是如果你能够理解它,它会大大帮助你进行编码。

-- -

2. Controllers 2.控制器

Following on from the above, you have to remember that your controller is really just a way to manipulate objects. 从上面开始,你必须记住你的控制器实际上只是一种操纵对象的方法。

Thus, if you're calling @workcategory , you need to appreciate where the object is going to come from and how it's going to be populated. 因此,如果你正在调用@workcategory ,你需要了解对象的来源以及它将如何填充。

You can make a helper method work_categories and use that. 您可以创建一个帮助方法work_categories并使用它。 Either define it directly in application_helper - or if you don't want to use helpers you can put this code in your ApplicationController 可以直接在application_helper中定义它 - 或者如果您不想使用帮助程序,可以将此代码放在ApplicationController中

class ApplicationController < ActionController::Base

  def work_categories
    Workcategory.all.order("created_at DESC")
  end
  helper_method :work_categories

end

Then in your view: 然后在你看来:

<ul class="dropdown-menu">
  <% work_categories.each do |workcategory| %>
    <li><%= workcategory.name%></li>
  <% end %>
</ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM