加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 所有视图都可以使用应用程序帮助程序方法吗?

发布时间:2020-12-17 02:41:00 所属栏目:百科 来源:网络整理
导读:Rails 4.1Ruby 2.0Windows 8.1 在我的助手/ application_helper.rb中,我有: def agents_and_ids_generator agents = Agent.all.order(:last) if agents agents_and_ids = [['','']] agents.each do |l| name = "#{l.first} #{l.last}" agents_and_ids [name
Rails 4.1
Ruby 2.0
Windows 8.1

在我的助手/ application_helper.rb中,我有:

def agents_and_ids_generator
    agents = Agent.all.order(:last)
    if agents
      agents_and_ids = [['','']]
      agents.each do |l|
        name = "#{l.first} #{l.last}"
        agents_and_ids << [name,l.id]
      end
      return agents_and_ids
    end
  end

在我的views / agents / form.html.erb中,我有以下内容:

<%= f.select :agent_id,options_for_select(agents_and_ids_generator) %>

在我的controllers / agents_controller.rb中,我有以下内容:

include ApplicationHelper

但是当我转到此视图时,我收到以下错误消息:

未定义的局部变量或方法`agents_and_ids_generator’用于#<#:0x00000006fc9148>

如果我将agents_and_ids_generator方法移动到helpers / agents_helper.rb,它可以正常工作.

我认为通过将方法放在应用程序帮助器中并将应用程序包含在控制器中,这些方法可用于视图.这个假设我不正确吗?

回答:

确保应用程序帮助程序未包含在控制器中,并添加了以下简化:

<%= f.collection_select :agent_id,Agent.all.order(:last),:id,:name_with_initial,prompt: true %>

#app/models/agent.rb
Class Agent < ActiveRecord::Base
   def name_with_initial
     "#{self.first} #{self.last}"
   end
end

解决方法

助手

底线答案是application_helper在您的所有视图中都可用.

Rails实际上在整个地方使用帮助程序 – 从form_for到其他内置的Rails方法.

由于Rails基本上只是一系列的课程和模块,在渲染视图时加载帮助程序,允许您在需要时调用它们.控制器在堆栈中处理得更早,因此您必须明确包含所需的帮助程序

重要 – 您不需要在ApplicationController中包含ApplicationHelper.它应该工作

你的问题

可能存在导致该问题的几种可能性;我有两个想法:

  1. Is your AgentsController inheriting from ApplicationController?
  2. Perhaps your inclusion of ApplicationHelper is causing an issue

奇怪的是你的AgentsHelper工作,而ApplicationHelper却没有.解释这一点的一种方法是Rails将根据正在操作的控制器加载一个帮助器,这意味着如果你不从ApplicationController继承,则不会调用ApplicationHelper.

你需要测试一下:

#app/controllers/application_controller.rb
Class AgentsController < ApplicationController
   ...
end

接下来,您需要删除控制器中的include ApplicationHelper.这只会使助手可用于该类(控制器),并且不会对您的视图产生任何影响

说到这一点,可能会导致加载ApplicationHelper的视图出现问题 – 这意味着你一定要测试从ApplicationController中删除它

方法

最后,使用collection_select可以大大简化您的方法:

<%= f.collection_select :agent_id,prompt: true %>

#app/models/agent.rb
Class Agent < ActiveRecord::Base
   def name_with_initial
       "#{l.first} #{l.last}"
   end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读