【问题标题】:ActiveRecords returning model object from a join tableActiveRecords 从连接表返回模型对象
【发布时间】:2012-11-20 20:00:11
【问题描述】:

我有以下数据库用于我正在构建的一个简单的闪存卡示例:

create_table "card_associations", :force => true do |t|
  t.integer  "card_id"
  t.integer  "deck_id"
end

create_table "cards", :force => true do |t|
  t.string   "question"
  t.string   "answer"
end

create_table "decks", :force => true do |t|
  t.string   "name"
  t.string   "description"
end

我已经在所有模型中通过关系设置了 has_many。 现在我希望能够从连接表中返回所有卡片的列表,给定卡片组 ID。 如果我运行查询:

CardAssociation.find_by_deck_id(3).card

它会重新运行第一张卡组 ID 为 3 的卡。但是当我尝试时。

CardAssociation.find_all_by_deck_id(3).card

我得到了错误

NoMethodError: # 的未定义方法 `card'

有人可以帮我解决这个问题吗?我觉得我犯了一个非常简单的错误。

感谢您的帮助

【问题讨论】:

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


    【解决方案1】:

    find_all_* 方法总是返回一个数组(可能为空)!

    CardAssociation.find_all_by_deck_id(3) # => Array of results
    CardAssociation.find_all_by_deck_id(3).first # => first result of the Array or nil if no result
    

    我建议你先阅读Ruby on Rails Style Guide,然后使用Rails3的方式用ActiveRecord查找对象:

    CardAssociation.where(:deck_id => 3) # => Array of results
    CardAssociation.where(:deck_id => 3).first # => first result of the Array if exists
    

    在您的情况下,可以在 Card 模型上设置范围:

    你说:“现在我希望能够返回连接表中所有卡片的列表,给定牌组 id

    class Card < ActiveRecord::Base
      scope :for_deck, lambda { |deck| joins(:card_associations).where('card_associations.deck_id = ?', deck.try(:id) || deck) }
    end
    

    这个范围可以像下面这样使用:

    Card.for_deck(deck) # returns an Array of Card objects matching the deck.id
    

    根据作用域中的定义,Card.for_deck(deck) 的参数可以是deck 对象deck_id(整数类型)

    希望这有帮助!

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 2018-08-17
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    相关资源
    最近更新 更多