看板 Ruby 關於我們 聯絡資訊
我想將三張表串接起來 可是發生了以下的錯誤 請問我有那裡沒有做對嗎 資料表的串接是否有其他的作法 感覺這種方式多張表串接的時候有點麻煩 # 錯誤訊息 http://ppt.cc/nev0 #schema.rb ActiveRecord::Schema.define(version: 20140916095516) do create_table "categories", force: true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end create_table "histories", force: true do |t| t.integer "item_id" t.integer "price" t.date "expend_at" t.datetime "created_at" t.datetime "updated_at" end create_table "items", force: true do |t| t.integer "category_id" t.string "name" t.datetime "created_at" t.datetime "updated_at" end end # model class History < ActiveRecord::Base belongs_to :item belongs_to :category end class Item < ActiveRecord::Base belongs_to :category has_many :history end class Category < ActiveRecord::Base has_many :item has_many :history, :through => :item end # controller class HistoryController < ApplicationController def index @histories = History.joins(:item).joins(:category).all end end #view <tbody> <% @histories.each do |history| %> <tr> <td><%= history.id %></td> <td><%= history.category.name %></td> <td><%= history.item.name %></td> <td><%= history.price %></td> <td><%= history.expend_date %></td> <td><%= history.created_at %></td> <td><%= history.updated_at %></td> </tr> <% end %> </tbody> -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.250.2.32 ※ 文章網址: http://www.ptt.cc/bbs/Ruby/M.1410866884.A.22B.html
goodplace: 你忘了把foreign key加進table裡了 09/16 22:27
mars90226: 應該要history.item.category吧? 09/16 23:38
ireullin: foreign key的部分可以講詳細點嗎 09/17 11:50
ireullin: 對這部分不是很了解,謝謝 09/17 11:50
goodplace: 你要把category_id加進histories table裡 09/17 21:39
ireullin: history.item.category.name不行耶 09/18 09:49
ireullin: 我是希望透過item這張表去關聯history與category的關係 09/18 09:50
ireullin: 在history中加入category_id比較不符合我的期望 09/18 09:51
goodplace: 仔細看了一下 發現你的model宣告根本不對 09/21 23:06
goodplace: has_many後面要加複數型 ex: has_many :histories 09/21 23:07
goodplace: guides.rubyonrails.org/association_basics.html 09/21 23:08
goodplace: 把上面那個連結網頁看一看 就知道要怎麼改了 09/21 23:08