我正在尝试从数据库中呈现随机对象。
步骤:1。generate button
(主页) - > 2.致电rand_task
(控制人员) - > 3. _rand_show.html.erb
(表格)
问题:它现在崩溃,但有一次它起作用。(我知道在编码中没有这样的东西,但我无法设法看到问题...) 主:
<%= form_for(:task, :url => {:action =>'rand_task', :id => 'random'}) do |f|%>
<%= render(:partial => "rand_show", :locals => {:f => f}) %></p>
<%end%>
控制器:
def rand_task
@task = Task.order('RANDOM()').first
end
形式:
<%= form_for(@task) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, :disabled=>true %>
<div class="field">
<%= f.label :category %><br />
<%= f.text_field :category, :disabled=>true %>
</div>
<div class="actions">
<%= f.submit "generate"%>
</div>
<% end %>
服务器:
Started GET "/" for 127.0.0.1 at 2012-09-13 19:35:56 +0300
Processing by TasksController#main as HTML
Rendered tasks/_rand_show.html.erb (0.8ms)
Rendered tasks/main.html.erb within layouts/application (1.6ms)
Completed 500 Internal Server Error in 4ms
ActionView::Template::Error (undefined method `model_name' for NilClass:Class):
1: <%= form_for(@task) do |f| %>
2: <div class="field">
3: <%= f.label :name %><br />
4: <%= f.text_field :name, :disabled=>true %>
app/views/tasks/_rand_show.html.erb:1:in `_app_views_tasks__rand_show_html_erb__183960888__627313568'
app/views/tasks/main.html.erb:2:in `block in _app_views_tasks_main_html_erb__298912262__627495408'
app/views/tasks/main.html.erb:1:in `_app_views_tasks_main_html_erb__298912262__627495408'
如果我添加<%= form_for(@task _=Task.new_ ) do |f| %>
而不是删除它,它只能用于一次实例
答案 0 :(得分:1)
此错误告诉您在这种情况下@task对象为nil。你需要确保你的&#34;任务&#34;中有记录。表
答案 1 :(得分:0)
修正:要访问本地变量,您需要在我的案例resources :tasks
中将表添加到config / routes.rb
编辑:服务器重启后问题仍然存在。