【发布时间】:2016-04-28 17:20:07
【问题描述】:
我已经创建了 2 个表
平台:
def change
create_table :platforms do |t|
t.string :name
t.timestamps null: false
end
end
游戏:
def change
create_table :games do |t|
t.string :title
t.text :description
t.string :image_url
t.decimal :price
t.integer :platform_id
t.timestamps null: false
end
add_index :games, :platform_id
end
然后这是我的游戏中的 _form.html.erb
<%= form_for(@game) do |f| %>
<% if @game.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@game.errors.count, "error") %> prohibited this game from being saved:</h2>
<ul>
<% @game.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :image_url %><br>
<%= f.text_field :image_url %>
</div>
<div class="field">
<%= f.label :price %><br>
<%= f.text_field :price %>
</div>
<div class="field">
<%= f.label :platform %><br>
<div>
<%= collection_select( :invoice, :platform_id, Platform.all, :id, :name, {}, {:multiple => false}) %>
</div>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
如果我创建新游戏并从选择输入中选择了 PlayStation,当我点击提交时,将显示 Games 表中的字段,例如 title、description、price、image_url 我想显示我之前选择的平台名称,例如 PlayStation 所以我添加了
<p>
<strong>Platform:</strong>
<%= @platform.name %>
</p>
从游戏中显示.html.erb,但当我尝试时,我得到错误
nil:NilClass 的未定义方法“名称”
我错过了什么吗? 我在这里尝试了一些解决方案,但仍然错误 谢谢
【问题讨论】:
-
您是否在控制器中设置了
@platform实例变量? -
什么是
@platform?另外,您确定创建游戏时platform_id不是nil?因为collection_select是错误的。 -
@Pavan 之前我已经制作了 3 个数据平台。即 PC、PlayStation 和 Xbox。我写 collection_select 有什么错误?
-
检查
platform_id表中platform_id的值并告诉我。 -
@pavan btw 我想我已经解决了:D 我已经将
collection_select更改为<%= collection_select( :game, :platform_id, Platform.all, :id, :name, {:multiple => false}) %>然后我将<%= @platform.name %>更改为<%= @game.platform.name %>我尝试添加游戏然后我选择平台和所有数据都可以显示。我不知道我所做的collection_select是否正确,但感谢您提供线索:D
标签: ruby-on-rails ruby database postgresql associations