【问题标题】:Rails - How to associate models in one direction onlyRails - 如何仅在一个方向上关联模型
【发布时间】:2012-07-12 17:35:54
【问题描述】:

大家好,

我是 Rails 新手,我觉得我在这里肯定遗漏了一些重要的东西,因为这似乎应该是一个很容易解决的问题。

我已经建立了一个Page 模型和一个Coord 模型(在入门教程的帮助下),并且Coord 成功belongs_to Page。我正在尝试应用类似的逻辑来制作另一个模型Comment,属于Coord,并且仅通过Coord 属于Page

我是否将:through 用于(我认为)只需要在一个方向链接的关联?如 Page

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

然后是评论模型:

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

【问题讨论】:

  • has_one :coord ,:through => :page 应该适用于您的情况
  • 您不需要在 Comment 模型中有一个 coord_id:integer 以便它可以将 Comment 引用到 Coord 吗?

标签: ruby-on-rails associations models


【解决方案1】:

页面

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

使用上面的,你不需要page_idcomments 表中。

参考:A Guide to Active Record Associations

【讨论】:

    猜你喜欢
    • 2010-10-15
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多