繁体   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