2015-11-02 74 views
0

我想要在show.html.erb中獲取像這樣的數據,但它不起作用。 如何從點表中獲取數據?Rails-如何爲已創建表創建視圖

這裏是代碼。

show.html.erb

<% @planaction.each do |action| %> 

     <hr> 
     <%= action.spot.name %> 
     <%= action.spot.description %> 
     <hr> 

     <%= action.title %> 
     <%= action.experience %> 

<% end %> 

plan.rb

class Plan < ActiveRecord::Base 

    has_many :plan_actions 

end 

plan_action.rb

class PlanAction < ActiveRecord::Base 
    belongs_to :plan 
    has_one :spot 
end 

spot.rb

class Spot < ActiveRecord::Base 
    belongs_to :plan_action 
end 

plan_actions_controller.erb

class PlanPagesController < ApplicationController 
    def show 
    @plan = Plan.find(params[:id]) 
    @planaction = @plan.plan_actions 
    end 
end 

這裏的錯誤消息

未定義的方法'名稱」的零:NilClass

和H ere是現貨表的遷移文件。

class CreateSpots < ActiveRecord::Migration 
    def change 
    create_table :spots do |t| 
     t.integer :spot_id 
     t.integer :plan_action_id 
     t.string :name 
     t.text :description 
     t.time :time_open 
     t.time :time_close 
     t.date :dayoff 
     t.string :address 
     t.integer :tel 
     t.string :image 
     t.string :image2 
     t.string :image3 

     t.timestamps null: false 
    end 
    end 
end 
+0

代碼看起來沒問題,你會得到什麼錯誤? –

+0

請解釋不行嗎? – Pavan

+0

這裏是一個錯誤未定義的方法'name'爲零:NilClass – vanhiro

回答

0

看起來不錯。

的問題是可能(不能肯定沒有看到你的日誌)的plan_action不具有關聯spot記錄。

爲了解決這個問題,你應該使用一些有條件的邏輯:

<% @planaction.each do |action| %> 
    <hr> 
    <% if action.spot %> 
     <%= action.spot.name %> 
     <%= action.spot.description %> 
     <hr> 
    <% end %> 

     <%= action.title %> 
     <%= action.experience %> 
<% end %> 

再次,這是炒作。我寫了答案,因爲我覺得最好提供一些關於如何解決它的想法。以上應該工作。

0

我也認爲Rich Peck,您沒有在plan table_id_id中對應於計劃操作的景點表中的記錄。

下列導軌慣例,我建議如下:

class PlanAction < ActiveRecord::Base 
    belongs_to :plan 
    has_one :spot 

    delegate :name, :description, to: :spot, prefix: true, allow_nil: true 
end 

,並在您的視圖:

<%= action.spot_name %> 
<%= action.spot_description %> 

最後,讓您的驗證糾正。例如,如果plan_action應該有一個點,那麼您需要使用嵌套表單來進行點和計劃操作。