我使用脚手架生成应用程序:。
rails generate scaffold server hostname:string
rails generate scaffold template remote_template_id:integer remote_template_name:string server:belongs_to
在我的rails控制器中,对于show方法,我想显示服务器拥有的所有模板。
当我运行show动作时,我收到以下错误:
undefined method `remote_template_id' for #<Array:0x007f6b44dc3370>
Extracted source (around line #5):
2:
3: <p>
4: <b>Remote template:</b>
5: <%= @template.remote_template_id %>
6: </p>
7:
以下是我的模板控制器中的代码:
def show
server=Server.find(params[:server_id])
@template=server.templates.all
logger.info "TEMPLATE OBJECT: " + @template.inspect
respond_to do |format|
format.html # show.html.erb
format.json { render json: @template }
end
end
如上所示,我使用记录器进行了一些调试输出,并且在rails服务器控制台中,对象确实正确显示。该对象包含我尝试传递到视图中的正确数据。
Server Load (0.2ms) SELECT "servers".* FROM "servers" WHERE "servers"."id" = ? LIMIT 1 [["id", "1"]]
Template Load (0.2ms) SELECT "templates".* FROM "templates" WHERE "templates"."server_id" = 1
TEMPLATE OBJECT: [#<Template id: 1, remote_template_id: 12, remote_template_name: "another_debian_derivative", server_id: 1, created_at: nil, updated_at: nil>]
Rendered templates/show.html.erb within layouts/application (0.9ms)
Completed 500 Internal Server Error in 6ms
ActionView::Template::Error (undefined method `remote_template_id' for #<Array:0x007f6b44dc3370>):
2:
3: <p>
4: <b>Remote template:</b>
5: <%= @template.remote_template_id %>
6: </p>
7:
8: <p>
app/views/templates/show.html.erb:5:in `_app_views_templates_show_html_erb___2503859911707707300_70049345896300'
app/controllers/templates_controller.rb:24:in `show'
数据库是犹太人,关系是可见的;我看到server_id被填充到模板表中。
sqlite> .tables
schema_migrations servers templates
sqlite>
sqlite> .schema servers
CREATE TABLE "servers" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "hostname" varchar(255), "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);
sqlite> select * from servers;
1|opennebula1|2014-01-28 11:03:02.393136|2014-01-28 11:03:02.393136
sqlite>
sqlite>
sqlite>
sqlite> .schema templates
CREATE TABLE "templates" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "remote_template_id" integer, "remote_template_name" varchar(255), "server_id" integer, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);
CREATE INDEX "index_templates_on_server_id" ON "templates" ("server_id");
sqlite> select * from templates;
1|12|another_debian_derivative|1||
sqlite>
最后,这里是错误的视图代码,我没有更改或添加任何内容,它是由脚手架生成的:
/app/views/templates$ cat show.html.erb
<p id="notice"><%= notice %></p>
<p>
<b>Remote template:</b>
<%= @template.remote_template_id %>
</p>
<p>
<b>Remote template name:</b>
<%= @template.remote_template_name %>
</p>
<p>
<b>Server:</b>
<%= @template.server %>
</p>
<%= link_to 'Edit', edit_template_path(@template) %> |
<%= link_to 'Back', templates_path %>
非常感谢这方面的帮助。谢谢。
答案 0 :(得分:1)
@ template = server.templates.all将返回模板对象的数组。在show.html.erb中,您尝试在此数组上调用remote_template_id而不是模板对象