Rails find_by和model外键

时间:2013-08-22 13:51:52

标签: ruby-on-rails ruby ruby-on-rails-3 foreign-keys

我现在正在研究Ruby on Rails,以提高自己作为开发人员的作用,所以我开始重写我的php网站来使用框架。
基本上该站点是源代码聚合器,因此我有一个语言模型和一个Source模型:

class Language < ActiveRecord::Base
  has_many :sources
end

class Source < ActiveRecord::Base
  belongs_to :language
end

与源表中的language_id外键绑定。
该网站的主要途径之一是:

get ':language_name/:source_name.html' => 'source#show'

例如:

/ruby/discover-if-a-number-is-prime.html

在SourceController中,我声明了以下内容:

class SourceController < ApplicationController
  def show
    language_name, source_name = params[:language_name], params[:source_name]
    @language = Language.find_by_name(language_name) || not_found
    @source = Source.find_by( name: source_name, language_id: @language.id ) || not_found
  end
end

有没有一种聪明的方法来执行这两个查询? 也许像是

@source = Source.find_by_name_and_language_name( source_name, language_name ) || not_found

我很抱歉,如果这是一个愚蠢的问题,我也正在阅读使用Rails 3.2的敏捷Web开发,但与此同时我想尝试一下。
感谢

2 个答案:

答案 0 :(得分:2)

根据对马立克答案的评论提问,使用joins

只能使用1个查询
@source = Source
  .joins(:language)
  .where(languages: { name: language_name })
  .where(sources: { name: source_name })
  .first

这将返回与source语言匹配的source_name匹配的第一个language_name

答案 1 :(得分:1)

怎么样:

@source = @language.sources.find_by_name(source_name)

或者,如果你想要ActiveRecord::RecordNotFound如果不存在正确的源(最终会导致渲染404页面),则会引发{/ p>}:

@source = @language.sources.find_by_name!(source_name)