我创建了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,当我点击提交时将显示来自游戏表的字段,如标题,描述,价格,image_url 我想显示之前选择的平台名称,如 PlayStation ,所以我添加了
<p>
<strong>Platform:</strong>
<%= @platform.name %>
</p>
来自游戏的show.html.erb但是当我尝试时,我收到错误
我错过了什么吗? 我在这里尝试了一些解决方案,但仍然是错误的 THXnil的未定义方法`name':NilClass
答案 0 :(得分:0)
您可以通过@game变量中的belongs_to关联来检索它。
<p>
<strong>Platform:</strong>
<%= @game.platform.name %>
</p>