Ruby on Rails:如何打印出一个字符串以及它显示在哪里?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7197169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on Rails: How to print out a string and where does it display at?
提问by John Lee
I know this is a trivial question. But I have search all over google but cannot find a simple answer to this question.
我知道这是一个微不足道的问题。但是我在谷歌上搜索过,但找不到这个问题的简单答案。
Basically I have a line that says <%= link_to 'Run it', :method => 'doIt' %>in the view, then in the corresponding controller, I have the doItmethod as follows:
基本上我有一行<%= link_to 'Run it', :method => 'doIt' %>在视图中说,然后在相应的控制器中,我有doIt如下方法:
def doIt
puts "Just do it"
end
I just want to check that if i click on Run it, it will output the string "Just do it". I ran this on localhost and there is no errors, but I can't find the output "Just do it" anywhere. It is not displayed in the rails console or rails server log. I just want to know where does puts output the string to , where to find it ?
我只是想检查一下,如果我点击运行它,它会输出字符串“Just do it”。我在 localhost 上运行了这个,没有错误,但我在任何地方都找不到输出“Just do it”。它不会显示在 rails 控制台或 rails 服务器日志中。我只想知道 puts 将字符串输出到哪里,在哪里可以找到它?
Round 2: So this is what I tried ....
第 2 轮:所以这就是我尝试过的......
Added this line in the index.html.erb (which is the root)
在 index.html.erb (这是根)中添加了这一行
<%= link_to 'Run it', :method => 'do_it' %>
and in the url, it is just basically http://localhost:3000/(since i route controller#index as root)
在 url 中,它基本上是http://localhost:3000/(因为我以 root 身份路由控制器#index)
The display is just an underlined 'Run it' that links to 'do_it' method in the controller.
显示只是一个带下划线的“运行它”,它链接到控制器中的“do_it”方法。
In the controller, i include this method
在控制器中,我包含了这个方法
def do_it
logger.debug "Just do it"
end
when i click on 'Run it', the url change to http://localhost:3000/gollum_starters?method=do_itand in the development.log, the following is written into it:
当我单击“运行它”时,url 更改为http://localhost:3000/gollum_starters?method=do_it并在 development.log 中写入以下内容:
Started GET "/gollum_starters?method=do_it" for 127.0.0.1 at 2011-08-25 15:27:49 -0700
Processing by GollumStartersController#index as HTML
Parameters: {"method"=>"do_it"}
[1m[35mGollumStarter Load (0.3ms)[0m SELECT "gollum_starters".* FROM "gollum_starters"
Rendered gollum_starters/index.html.erb within layouts/application (3.6ms)
Completed 200 OK in 16ms (Views: 7.7ms | ActiveRecord: 0.3ms)
Additionally, i tried all the logger.error/info/fatal/etc ... and Rails.logger.error/info/fatal/etc, all did not print out the line "Just do it" in the development log
此外,我尝试了所有 logger.error/info/fatal/etc ... 和 Rails.logger.error/info/fatal/etc,都没有在开发日志中打印出“Just do it”行
@Paul: I did not touch the environment folder or file, i assume by default when a new rails app is created, it is in development ?
@Paul:我没有触及环境文件夹或文件,我假设默认情况下创建新的 rails 应用程序时,它正在开发中?
@Maz: Yes you are right, I am just trying to test if the do_it method is getting called. To do that, I just want to print something out in the controller. Can't think of any way simpler that just print a string out, but this problem is making me miserable. I am just using textmate, no IDE.
@Maz:是的,你是对的,我只是想测试 do_it 方法是否被调用。为此,我只想在控制器中打印出一些东西。想不出任何更简单的方法来打印一个字符串,但是这个问题让我很痛苦。我只是使用 textmate,没有 IDE。
Round 3:
第 3 轮:
@Paul thx alot, but i encountered error
@Paul thx 很多,但我遇到了错误
My routes files is now:
我的路线文件现在是:
resources :gollum_starters
root :to => "gollum_starters#index"
match 'gollum_starters/do_it' => 'gollum_starters#do_it', :as => 'do_it'
My index.html.erb is now:
我的 index.html.erb 现在是:
<%= link_to "Do it", do_it_path %>
My gollum_starters_controller.rb
我的 gollum_starters_controller.rb
def do_it
logger.debug 'Just do it'
end
I am getting this error:
我收到此错误:
Couldn't find GollumStarter with ID=do_it
找不到 ID=do_it 的 GollumStarter
the error is in here, 2nd line:
错误在这里,第二行:
def show
@gollum_starter = GollumStarter.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @gollum_starter }
end
end
I wonder why does it route to show ? When i click do_it, it actually goes to localhost:3000/gollum_starters/do_it which is correct, but apparently the error points to the show method ?
我想知道为什么它会路由显示?当我单击 do_it 时,它实际上转到 localhost:3000/gollum_starters/do_it,这是正确的,但显然错误指向 show 方法?
Round 4:
第 4 轮:
@Paul, i shifted resources :gollum_starters down:
@Paul,我转移了资源:gollum_starters:
root :to => "gollum_starters#index"
match 'gollum_starters/do_it' => 'gollum_starters#do_it', :as => 'do_it'
resources :gollum_starters
but got this error (omg i wanna kill myself),
但是遇到了这个错误(天哪,我想自杀),
Template is missing
Missing template gollum_starters/do_it with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths "~/project_name/app/views"
模板丢失
缺少模板 gollum_starters/do_it 和 {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]}查看路径“~/project_name/app/views”
:/
:/
---------- Answer to Round 4------------
----------对第 4 轮的回答------------
Basically as the error explains, there is no template(i.e a webpage) to show hence error thrown. The solution is to add a redirect_to , in this case I redirect to root_url.
基本上正如错误所解释的那样,没有模板(即网页)可以显示,因此会引发错误。解决方案是添加一个 redirect_to ,在这种情况下我重定向到 root_url。
def do_it
logger.debug 'Just do it'
redirect_to(root_url)
end
Everything works now, "Just do it" finally outputs to development.log and the rails server console.
现在一切正常,“Just do it”最终输出到 development.log 和 rails 服务器控制台。
Thank you Maz and Paul and Andrew for helping me out. Learn a lot.
感谢马兹、保罗和安德鲁帮助我。学到很多。
采纳答案by Paul.s
That link_todoes not do what you think it does the value for :methodis referring to the HTTPverbs.
这link_to不会做你认为它的价值:method是指HTTP动词。
Taken from the docs for ActionView::Helpers::UrlHelper
取自ActionView::Helpers::UrlHelper的文档
:method- Symbol of HTTP verb. Supported verbs are :post, :get, :delete and :put. By default it will be :post.
:method- HTTP 动词的符号。支持的动词有:post、:get、:delete 和:put。默认情况下它将是 :post。
You would need to define a route in your routes.rbfile that uses your method
您需要在routes.rb使用您的方法的文件中定义一个路由
# The order of routes is important as the first matched will be used
# therefore the match needs to be above 'resources :controller'
match 'controller/do_it' => 'controller#do_it', :as => 'do_it'
resources :gollum_starters # <--- This needs to be below the match or this will catch first
- The
controller/do_itis the route to be matched - The
controller#do_itis the controller followed by the action to be used (separated by#) - The value for
:ascreates the pathdo_it_paththat can be used in yourlink_to
- 的
controller/do_it是要匹配的路径 - 的
controller#do_it是要使用的控制器随后动作(相隔#) - 的值
:as创建do_it_path可用于您的路径link_to
Your link_tomay look something like
你link_to可能看起来像
<%= link_to "Do it", do_it_path %>
And to complete the lifecycle of a request you will need to add a viewto be rendered
并且要完成请求的生命周期,您需要添加view要呈现的
app/views/gollum_startes/do_it.html.erb # <-- Add file
SummaryDoing all of this creates a bit of a mess just to print something out to the logs, but it should help you understand the whole lifecycle a bit better now. Plus this answers serves as a document to help you rewind this mess.
总结做所有这些只是为了将一些东西打印到日志中会造成一些混乱,但它现在应该可以帮助您更好地理解整个生命周期。此外,此答案可作为帮助您扭转这一混乱局面的文档。
回答by Andrew
You are not understanding what "method" means in the context of a link.
您不了解链接上下文中的“方法”是什么意思。
The "method" here refers to the request method, which means the kind of request you are asking the browser to make. From the perspective of a RESTfulapplication like Rails there are four relevant request types: GET, POST, PUT, and DELETE. These request types affect how the controller responds to a request.
这里的“方法”指的是请求方法,即您要求浏览器发出的请求类型。从像 Rails 这样的RESTful应用程序的角度来看,有四种相关的请求类型:GET、POST、PUT 和 DELETE。这些请求类型会影响控制器对请求的响应方式。
- GET => INDEX or SHOW
- POST => CREATE
- PUT => UPDATE
- DELETE => DESTROY
- GET => 索引或显示
- 发布 => 创建
- 放置 => 更新
- 删除 => 销毁
There are two other "standard" rails actions, NEW and EDIT. These are GET requests to present an interface to the user. NEW gives you a form to POST (CREATE) a new object, and EDIT gives you a form to PUT (UPDATE) and existing one.
还有另外两个“标准”rails 操作,NEW 和 EDIT。这些是向用户呈现界面的 GET 请求。NEW 为您提供了一个用于 POST (CREATE) 新对象的表单,EDIT 为您提供了一个用于 PUT (UPDATE) 和现有对象的表单。
See the rails guidefor more on how HTTP Verbs relate to CRUD operations.
有关HTTP Verbs 如何与 CRUD 操作相关的更多信息,请参阅rails 指南。
The important, basic thing to understand is that links, by default, are GET requests, and forms, by default, are POST requests.
要理解的重要的基本事情是,默认情况下,链接是 GET 请求,默认情况下,表单是 POST 请求。
So, when your link looks like this:
因此,当您的链接如下所示时:
<%= link_to 'Run it', :method => 'do_it' %>
...it is bogus. There is no such HTTP method as "do_it", so you're not triggering anything. Because there is no such method, Rails actually passes this on as a parameter of the URL. Hence if you click that you should see your url bar now says ?method=do_itat the end.
……是假的。没有像“do_it”这样的 HTTP 方法,所以你不会触发任何东西。因为没有这样的方法,Rails 实际上将它作为 URL 的参数传递。因此,如果您单击它,您应该会看到您的 url 栏现在显示?method=do_it在最后。
There are several problems with what you're trying to do. First of all, the link_to helperexpects at least two arguments: 1, the text for the link, and 2 the HREF for the link. So, you really need to use:
您尝试执行的操作存在多个问题。首先,link_to 助手至少需要两个参数:1,链接的文本,2 链接的 HREF。所以,你真的需要使用:
link_to 'Run it', url
Second, you need to know what URL to pass to get your controller action.
其次,您需要知道要传递什么 URL 来获取控制器操作。
Please be familiar with the following rails convention:When referring to a controller action you can abbreviate it using the form: controller_name#controller_action. e.g. pages#showor articles#index.
请熟悉以下 rails 约定:当提到控制器操作时,您可以使用以下形式将其缩写:controller_name#controller_action。例如pages#show或articles#index。
Assuming your controller is called ExamplesController, you can manually trigger the seven standard controller actions as follows:
假设您的控制器被调用ExamplesController,您可以手动触发七个标准控制器操作,如下所示:
link_to 'examples#index', '/examples'
link_to 'examples#show', '/examples/123' # 123 is the id of a specific example
link_to 'examples#new', '/examples/new'
link_to 'examples#create', '/examples', :method => :post
link_to 'examples#edit', '/examples/123/edit'
link_to 'examples#update', '/examples/123', :method => :put
link_to 'examples#destroy', '/examples/123', :method => :delete
Note that in the above, INDEX, SHOW, NEW, and EDIT are all GET requests. You could specify :method => :getbut that is unnecessary
注意上面的INDEX、SHOW、NEW、EDIT都是GET请求。您可以指定,:method => :get但这是不必要的
To abstract this away and take care of assigning the ID when required Rails provides path helpers.
将其抽象出来并在需要时负责分配 ID,Rails 提供了路径助手。
So, to repeat the above using the path helpers you could use:
因此,要使用您可以使用的路径助手重复上述操作:
link_to 'examples#index', examples_path
link_to 'examples#show', example_path( @example )
link_to 'examples#new', new_example_path
link_to 'examples#create', examples_path, :method => :post
link_to 'examples#edit', edit_example_path( @example )
link_to 'examples#update', example_path( @example ), :method => :put
link_to 'examples#destroy', example_path( @example ), :method => :delete
Now, you get these path helpers from the router, and they are defined in your routes.rbfile. Within that file if you define:
现在,您可以从路由器获得这些路径助手,并且它们已在您的routes.rb文件中定义。在该文件中,如果您定义:
resources :examples
...then you will get all the path_helpers above.
...然后你会得到上面所有的 path_helpers。
If you are using a normal RESTful controller and you want to add a custom action, then you need to make one decision: does the action operate on the entire set of objects handled by that controller (like index) or just a single specific one (like show). The reason this is important is this tells the router whether the new action you're defining needs to receive a record ID as part of the request.
如果您使用的是普通 RESTful 控制器并且想要添加自定义操作,那么您需要做出一个决定:该操作是在该控制器处理的整个对象集(如索引)上操作还是仅对单个特定对象进行操作(喜欢表演)。这很重要的原因是它告诉路由器您定义的新操作是否需要接收记录 ID 作为请求的一部分。
If you want to act on the entire collection of objects, you define:
如果要对整个对象集合进行操作,请定义:
resources :examples do
collection do
get 'do_it'
end
end
If you want to act on just a single member of the collection you define:
如果您只想对您定义的集合的单个成员进行操作:
resources :examples do
member do
get 'do_it'
end
end
Where I wrote 'get' in the examples above you can use any of the four verbs -- GET is normally what you do if you want to show a page, and POST is normally what I'd use if you're submitting a form. You can also write this shorthand like so:
我在上面的例子中写了“get”的地方你可以使用四个动词中的任何一个——如果你想显示一个页面,GET通常是你所做的,而如果你提交表单,我通常会使用POST . 你也可以像这样写这个速记:
resources :examples do
get 'do_it', :on => :collection
post 'something', :on => :member
end
For more on defining custom controller actions, see the rails guide.
有关定义自定义控制器操作的更多信息,请参阅rails 指南。
Now that you've defined a route, you should run rake routesin terminal to see the name of the new path helper. Let's assume you added do_itas a collection method, your path helper would be: do_it_examples_path.
现在您已经定义了一个路由,您应该rake routes在终端中运行以查看新路径助手的名称。让我们假设你添加do_it的收集方法,你的路径帮手会是:do_it_examples_path。
Now then, back to your link, if you put:
现在,回到您的链接,如果您输入:
<%= link_to 'Do it.', do_it_examples_path %>
... then you would trigger the do_itaction. When the action is triggered your putsshould normally render to the server log (assuming you're running rails s in a terminal window you should see it right after started GET on examples#do_it...).
...然后您将触发该do_it操作。当操作被触发时,您puts通常应该呈现到服务器日志(假设您在终端窗口中运行 rails s,您应该在started GET on examples#do_it...之后立即看到它)。
Now, in the browser you would get a missing template error as a GET request is going to expect to render a view, but that's a subject for another question. Basically, now you should understand what the controller actions are, how you get to them. If you want to learn more about what to do with your controller action, see the guide:)
现在,在浏览器中,您将收到一个缺少模板错误,因为 GET 请求将期望呈现视图,但这是另一个问题的主题。基本上,现在您应该了解控制器操作是什么,您如何获得它们。如果您想了解有关如何处理控制器操作的更多信息,请参阅指南:)
I hope you understand what's going on now. Feel free to ask questions.
我希望你明白现在发生了什么。随意问的问题。
回答by Maz
You want to use the Rails logging mechanism:
您想使用 Rails 日志记录机制:
http://guides.rubyonrails.org/debugging_rails_applications.html#sending-messages
http://guides.rubyonrails.org/debugging_rails_applications.html#sending-messages
This means that even if you don't launch the server using rails sthe output will still go to the right place.
这意味着即使您不使用rails s输出启动服务器,它仍然会转到正确的位置。

