STI类型列

时间:2015-11-30 20:20:57

标签: ruby-on-rails ruby activerecord sti

我有一个User模型,可以有很多Websites。例如,我将能够调用User.websites,它将获取用户拥有的所有网站的ActiveRecord数组。但每个网站都使用单表继承(STI)和type列来确定网站的类型,如商业广告,广告或论坛。我的问题是,如果用户有一个特定类型的网站,我是要创建一个运行函数的case / when语句。例如:

@user = User.first
case @user.websites
    when includes?(Commercial)
        'This user has a commercial website'
    when includes?(Forum)
        'This user has a forum website'
    when include?(Ad)
        'This user has a advertisement website'
end

有没有人知道做这种事情的最佳方法?

3 个答案:

答案 0 :(得分:4)

执行此操作的最短方法是使用 private void Application_DocumentOpen(Microsoft.Office.Interop.Word.Document doc) { //Test revisions // expected text, as taken from screengrab example above. Includes // text removed in a revision string expectedText = "Video provides a powerful way to help you prove your point."; // make sure that we're in print view if (doc.ActiveWindow.View.Type != Word.WdViewType.wdPrintView) { doc.ActiveWindow.View.Type = Word.WdViewType.wdPrintView; } // attempt to ensure that document revisions are marked up inline. Does not accomplish anything Word.View vw = doc.ActiveWindow.View; vw.MarkupMode = Word.WdRevisionsMode.wdInLineRevisions; vw.RevisionsView = Word.WdRevisionsView.wdRevisionsViewFinal; // attempt to locate text. Will fail if revisions are not marked up inline (deletion is not part of document content range otherwise) var locatedRange = OccurrenceOfText(doc.Content, expectedText); } // extension method to locate text inside a range. Searching entire Content in this example private static Word.Range OccurrenceOfText(Word.Range rng, string text) { rng.Find.Forward = true; rng.Find.Format = false; rng.Find.Execute(text); if (!rng.Find.Found) { throw new Exception("Unable to locate text! Are Revisions marked up inline?"); } // return brand new range containing located content return rng; //.Document.Range(rng.Start, rng.End); } 方法。只需一行!

map

或者如果你想在数组中包含这些字符串。

   @user.websites.select(:type).uniq.map{
       |x| puts "This user has a #{x.type.downcase} website" 
   }

如果要运行功能。我建议以友好的方式命名函数,例如@user.websites.select(:type).uniq.map{|x| x.type.downcase} commercial_cost等。这样您就可以使用forum_cost方法使代码紧凑。

send

答案 1 :(得分:2)

def types
  'This user has following websites: ' +  
     websites.pluck(:type).map(&:downcase).join(', ')
end

答案 2 :(得分:0)

#user.rb

def return_data(*types)
  types.each do |t|
    if Website.where(:user_id => self.id, :type=> t).length>0
      send "method_for_owners_of_#{t}_site"
    end
  end
end

def method_for_owners_of_Commercial_site
end
#...

 @user.return_data(["Commercial"])
 @user.return_data(["Commercial", "Ad"])
 ...

根据Rails API

  

当您执行Firm.create(名称:“37signals”)时,将保存此记录   在公司表中,类型=“公司”。