2016-04-28 61 views
0

我已经建立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从选择输入,当我点击提交,这将是秀场从游戏表像标题,描述,价格,图片网址我想显示的名称我所的PlayStation像以前一样所选择的平台,所以我说

<p> 
    <strong>Platform:</strong> 
    <%= @platform.name %> 
</p> 

从游戏到show.html.erb但是当我尝试它,我得到错误

未定义方法名称为零:NilClass

我错过了什么吗? 我在这里尝试了一些解决方案,但仍然错误 thx

+0

您是否在控制器中设置了@平台实例变量? – Uzbekjon

+0

什么是@平台?你是否确定在创建游戏时'platform_id'不是'nil'?因为'collection_select'是错误的。 – Pavan

+0

@Uzbekjon尚未 – June

回答

0

您可以通过@game变量的belongs_to关联检索它。

<p> 
    <strong>Platform:</strong> 
    <%= @game.platform.name %> 
</p> 
+0

仍然得到未定义的方法'name'为零:NilClass – June

+0

关联是否正确设置。提交表单时什么是日志消息。 – joewoodward

+0

检查strong_parameters是否没有将platform_id参数列入黑名单。还要检查轨道控制台中的游戏记录,确保您确实已将其正确保存。 collection_select对我来说看起来有点可疑 – joewoodward