【问题标题】:Rails3 has_and_belongs_to_many - error on getting an attribute from join tableRails3 has_and_belongs_to_many - 从连接表获取属性时出错
【发布时间】:2011-09-20 02:17:58
【问题描述】:

鉴于我有以下结构:

class A < ActiveRecord::Base
  has_and_belongs_to_many :bs, :class_name => "B", :join_table => "ab"
end

class AB < ActiveRecord::Base
  #ab has a date column "creation_date"
  #ab also has a text column "creatior"
end

class B < ActiveRecord::Base
end

我成功检索到rails console中的“creation_date”属性

console> A.find(1).bs.first.creation_date
        => "14/08/1874"

在控制器中

@a = A.find(1)
@bs = a.bs

但是在视图中使用它(部分),我得到了以下错误

bs.each do |b|
  b.b_attribute #this is O.K.
  b.creation_date # cause error =>    undefined method `creation_date` for #<B:...>
end

 # also try to debug in partial
 A.find(1).bs.first.creation_date #=> this return data correctly

如上所示的问题,什么可能导致undefined method,而直接属性仍然可以访问。

有人知道我的代码有什么问题吗?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord has-and-belongs-to-many


    【解决方案1】:

    处理中间模型时,不应使用has_and_belongs_to_many。该方法仅在连接表不是模型时有效。您需要明确区分 modeltable 的概念。在 Rails 中,您很少能够访问底层表,通常您需要处理包装模型。

    如果您的连接表除了AB 的外键之外还有其他内容,并且您需要访问这些额外的数据,那么它需要是一个模型。在你的情况下,它是,但你没有使用正确的关系。它应该是这样的:

    class A < ActiveRecord::Base
      has_many :abs
      has_many :bs, :through => :abs
    end
    
    class AB < ActiveRecord::Base
    end
    
    class B < ActiveRecord::Base
    end
    

    之后,访问creation_datecreator 应该通过AB 模型完成,因为它确实是属于它的属性。

    在这里查看示例的快速解释:http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-01
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多