【问题标题】:HABTM - undefined methodHABTM - 未定义的方法
【发布时间】:2013-01-09 09:44:44
【问题描述】:

我正在尝试在我的 Rails 应用程序中创建一个简单的书签功能。

这是我的模型:

# post.rb
class Post < ActiveRecord::Base
  has_and_belongs_to_many :collections
end

# collection.rb
class Collection < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

# collections_posts.rb
class CollectionsPosts < ActiveRecord::Base
end

现在我正在尝试写一个非常简单的东西——在postcollection 之间添加一个关系:

post = Post.find(1)
collection = Collection.find(1)
collection.posts << collection

这段代码给了我以下错误:

undefined method `posts' for #<ActiveRecord::Relation:0x00000100c81da0>

我不知道为什么没有 posts 方法,因为我有很多其他关系以完全相同的方式定义并且它们运行良好,尽管它们不是 HABTM。

你能告诉我我的代码有什么问题吗?

【问题讨论】:

  • 首先我猜你的CollectionsPosts 在这里没有用,使用has_many through 关联时必须要有“加入模型”。您的数据库中是否有所需的表,即collections_posts
  • 我添加它只是为了检查它是否会改变任何东西,但它不会。无论如何-无论是否有CollectionsPosts 模型,我都会收到此错误;)是的,我确实有这张桌子
  • 很奇怪,您收到ActiveRecord::Relation 的错误,我认为这意味着collection 是一个关系。 find 的结果应该是实际记录,而不是关系。你确定你没有做任何这里没有显示的事情吗?
  • 这里是整个方法(User.collect_post()。它在User 模型和Collection 属于_to User)但我找不到任何问题:gist.github.com/4492062
  • 那是你的问题。我会发布一个答案。

标签: ruby-on-rails ruby-on-rails-3 rails-activerecord


【解决方案1】:

我认为你真的可以让你的 collect_post 方法更简单,这样应该可以工作:

def collect_post(post, collection_title = 'Favourites')

  # Find a collection by its name
  collection = Collection.find_by_name(title: collection_title) # this will return a collection object and not an ActiveRecord::Relation

  # if there is no such collection, create one!
  if collection.blank?
    collection = Collection.create user: self, title: collection_title
  end

  collection.posts << post

end

请注意,可能有更好的方法来做到这一点,但它比你最初所做的更短,应该修复你原来的错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 2013-06-11
    • 2010-12-30
    • 2019-12-25
    • 2021-07-25
    • 2019-06-20
    相关资源
    最近更新 更多