简体   繁体   English

Ruby on Rails中的未定义方法

[英]Undefined Method in ruby on rails

I am new to Ruby on Rails and im stuck on something so simple but I just cant figure it out. 我是Ruby on Rails的新手,我只喜欢这么简单的东西,但是我无法弄清楚。

I scaffolded a Video model, controller and view and then created a Welcome controller for the home page. 我搭建了视频模型,控制器和视图,然后为主页创建了“欢迎”控制器。

I manually created an index.html.erb file in the welcome view folder and proceeded to route the home page to Welcome#index. 我在welcome view文件夹中手动创建了一个index.html.erb文件,然后将主页路由到Welcome#index。 All working fine for now. 目前一切正常。

Thing is when I define a method in the welcome_controller like this 就是这样,当我像这样在welcome_controller中定义方法时

def foo
   puts 'Hello'
end

and I call it in the welcome/index.html file like this 我在这样的welcome / index.html文件中称呼它

<%= foo %>

I get the following error: undefined local variable or method `foo' for #<#:0x39675d8> 我收到以下错误:#<#:0x39675d8>的未定义局部变量或方法'foo'

Controller actions aren't view helpers, you'll want to put foo in either application_helper.rb or welcome_helper.rb to use it like you are and change it to remove the puts , like this: 控制器动作不是视图助手,您需要将foo放在application_helper.rbwelcome_helper.rb以按welcome_helper.rb使用它,并更改它以删除puts ,如下所示:

def foo
  'Hello'
end

This will insert Hello into your view (which is what I think you were expecting) 这会将Hello插入到您的视图中(这正是我所期望的)

Based on your comments below, you should probably be using a scope in your model... 根据下面的评论,您可能应该在模型中使用scope

scope :highlighted -> { (where(highlight: true) }

... to return highlighted records from your controller... ...从控制器返回突出显示的记录...

@highlighted = Videos.highlighted

... and then iterate over @highlighted in your view... ...然后在您的视图中遍历@highlighted ...

<% @highlighted.each do |video| %>
<%= ...do something with video here... %>
<% end %>

please read more about all this here: 请在此处详细了解所有这些信息:

http://guides.rubyonrails.org/index.html http://guides.rubyonrails.org/index.html

and specificially for scopes here... 特别是这里的范围...

http://guides.rubyonrails.org/active_record_querying.html http://guides.rubyonrails.org/active_record_querying.html

You can't call arbitrary "things" in the controller. 您不能在控制器中调用任意的“事物”。

What's exposed in the controller are its instance variables, eg, @foo . 控制器中公开的是其实例变量,例如@foo

If you really want to call a method that uses puts , put it in a helper, eg, welcome_helper.rb (or whatever the convention would be). 如果您确实要调用使用puts的方法,请将其放在帮助程序中,例如, welcome_helper.rb (或任何约定)。

Note, however, that this won't do what you appear to believe it will, namely, put a "Hello" on the web page. 但是请注意,这不会像您认为的那样起作用,即在网页上放置“ Hello”。 You're basically writing directly to the console, not even the log file. 您基本上是直接写到控制台,甚至不是日志文件。

What specifically are you trying to accomplish? 您到底想完成什么?

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

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