簡體   English   中英

Rails-如何僅在一個方向上關聯模型

[英]Rails - How to associate models in one direction only

大家好

我是Rails的新手,我覺得我肯定在這里缺少重要的東西,因為看來這應該是一個容易解決的問題。

我已經建立了一個Page模型和一個Coord模型(在入門教程的幫助下),並且Coord成功地belongs_to Page 我正在嘗試應用類似的邏輯來制作另一個模型Comment ,該模型屬於Coord ,並且僅屬於Page via Coord

我是否使用:through關聯(我認為)僅需要在一個方向上進行鏈接? 如在頁面<坐標<評論? 目前,我有:

class Page < ActiveRecord::Base
  attr_accessible :description, :name
  has_many :coords
  has_many :comments, :through => :coords
end

坐標模型:

class Coord < ActiveRecord::Base
  belongs_to :page
  has_many :comments
  attr_accessible :coordinates, :x, :y
  validates :x, :presence => true
  validates :y, :presence => true
end

然后是Comment模型:

class Comment < ActiveRecord::Base
  belongs_to :coord
  belongs_to :page
  attr_accessible :body
end

我仍然不斷收到有關comments是未定義方法或未定義關聯的錯誤。 抱歉,如果這是一個常見問題,我個人不認識Rails,並且該文檔僅提供了一些與我相去甚遠的示例(據我所知)。 謝謝

編輯:添加了數據庫架構

ActiveRecord::Schema.define(:version => 20120712170243) do

  create_table "comments", :force => true do |t|
    t.text     "body"
    t.integer  "coord_id"
    t.integer  "page_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  add_index "comments", ["coord_id"], :name => "index_comments_on_coord_id"
  add_index "comments", ["page_id"], :name => "index_comments_on_page_id"

  create_table "coords", :force => true do |t|
    t.string   "coordinates"
    t.integer  "x"
    t.integer  "y"
    t.integer  "page_id"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

  add_index "coords", ["page_id"], :name => "index_coords_on_page_id"

  create_table "pages", :force => true do |t|
    t.string   "name"
    t.string   "description"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

end

class Page < ActiveRecord::Base
  has_many :coords
  has_many :comments, :through => :coords
end

協調

class Coord < ActiveRecord::Base
  belongs_to :page
  has_many :comments
end

評論

class Comment < ActiveRecord::Base
  belongs_to :coord
  has_one :page, :through => :coord
end

使用以上內容,您不需要在comments表中使用page_id

參考: Active Record關聯指南

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM