Rails has_many 求助

secondrocker · 2013年03月09日 · 最后由 simonykq 回复于 2013年04月11日 · 2704 次阅读

各位大神,我有两个 model,分别是 user 和 card,通过一个中间 model carding 相互 has_many,其中中间 model 记录了一个字段,叫做 start_date,那么我怎么访问某个 user 的某个 card 的 start_date 呢?

1 楼 已删除

是不是应该通过中间 model 来查询 (伪代码)

u1 = User.where(....)
card1 = Card.where(...)

start_date = Carding.where( user_id: u1.id, card_id: card1.id)

额,你只说了你的表结构,缺没给查询条件。。。这怎么解决呢

#2 楼 @blueplanet 我要是遍历 user 的所有 card,那么那个 start_date 又怎么获取呢,sql 的话弄个左链接搞定,rails 怎么做多表查询呢?

你直接贴两段代码上来不是能很好说明问题。。 #4 楼 @secondrocker 可以用 joins 或者 includes 的方式来进行查询 http://guides.rubyonrails.org/active_record_querying.html

@cards=Card.find_by_sql("select c.*,b.start_date from users a,cardings b ,cards c where a.id=b.user_id and b.card_id=c.id and a.id=#{params[:id]}") 
class Card < ActiveRecord::Base
  attr_accessible :description, :last_months, :name
  has_many :cardings
  has_many :users ,:through=>:carding
end

class Carding < ActiveRecord::Base
  attr_accessible :card_id, :start_date, :user_id
  belongs_to :card
  belongs_to :user
end

class User < ActiveRecord::Base
  attr_accessible :address, :hashed_password, :name, :qq, :salt, :sex, :tel, :user_code
  has_many :cardings
  has_many :cards ,:through=>:cardings
end

@user.cards.select("cards.* carding.*").joins("INNER JOIN cardings on cardings.card_id = cards.id").where("cardings.start_date = ?", "YOUR DATE")

需要 登录 后方可回复, 如果你还没有账号请 注册新账号