Re: [問題] 請問ROR資料表的關聯

作者: matrixki (New Season)   2014-09-10 22:54:56
※ 引述《ireullin (raison detre)》之銘言:
: 請問大家
: 我現在想要秀出 History 這張表的內容
: 但是 item_id 的部分我想 join 到 item這張表的ID
: 以下是我的程式碼
: 但是我得到了這樣的錯誤
: http://ppt.cc/dl2K
: 請問我哪裡做錯了嗎
: 我使用的是Rails4 Ruby 2.0
: #schema
: ActiveRecord::Schema.define(version: 20140908145413) do
: create_table "histories", force: true do |t|
: t.integer "item_id"
: t.integer "price"
: t.date "expend_date"
: t.datetime "created_at"
: t.datetime "updated_at"
: end
: create_table "items", force: true do |t|
: t.string "category"
: t.string "name"
: t.datetime "created_at"
: t.datetime "updated_at"
: end
: end
: # model
: class Item < ActiveRecord::Base
: belongs_to :history
: end
: class History < ActiveRecord::Base
: has_many :items
: end
: # controller
: class HistoryController < ApplicationController
: def index
: @histories = History.joins(:item).all
: end
: end
: #view
: <% @histories.each do |history| %>
: <tr>
: <td><%= history.id %></td>
: <td><%= history.item_id %></td>
: <td><%= item.name %></td>
: <td><%= history.price %></td>
: <td><%= history.expend_date %></td>
: <td><%= history.created_at %></td>
: <td><%= history.updated_at %></td>
: </tr>
: <% end %>
因為你一個history對到多個items
所以你的view那邊也要跟著對應寫each
<% history.items.each do |item| %>
<%= item.name %>
<% end %>

Links booklink

Contact Us: admin [ a t ] ucptt.com