基于条件的Rails将模型分配给变量

时间:2013-02-28 08:22:43

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

我有以下方法:

def self.get_rec(product, type)
  if type == "A"
    db = Pwvav
  elsif type == "B"
    db = Pwbab
  elsif type == "C"
    db = Pwvub
  else type == "D"
    db = Tic
    db.find_by_id(product.id).recommendation.split(",").each do |rec|
      r = Recommendation.find_by_id(rec)
      pr = Model.new(:rating_set => rating_set.id, :recommendation_id => r.id, :product_id => product.id)
      pr.save
    end
  end
end

当我运行该方法时,db.find无法正常工作。例如,如果将db.find_by_id(product.id).recommendation.split(",").each do |rec|替换为Pwvav.find_by_id(product.id).recommendation.split(",").each do |rec|,则可行。如何根据type等于什么来选择要调用的模型?

2 个答案:

答案 0 :(得分:1)

你的错误,如果我是对的,那就是你的结构。 find_by_id代码在else中,因此当type不是'D'时,它不会创建其他记录。尝试以下我认为更易读的代码

def self.get_rec(product, type)
  db = case type
       when 'A' then Pwvav
       when 'B' then Pwbab
       when 'C' then Pwvub
       when 'D' then Tic
       end

  db.find_by_id(product.id).recommendation.split(",").each do |rec|
    r = Recommendation.find_by_id(rec)
    pr = Model.new(rating_set: rating_set.id, recommendation_id: r.id, product_id => product.id)
    pr.save
  end
end

答案 1 :(得分:0)

你还没有关闭你的“if - elsif - else条件,然后是find,find_by_id的最后一个块,而你的new只在输入=='D'时执行。

之后插入一个结尾
db = Tic