【问题标题】:SQL Joins in RailsRails 中的 SQL 连接
【发布时间】:2009-07-24 17:58:38
【问题描述】:

尝试使用 rails 中的现有数据库。以下在 MySQL 控制台中工作得很好:

select title,blog_name from exp_weblog_titles JOIN exp_weblogs ON exp_weblog_titles.weblog_id = exp_weblogs.weblog_id LIMIT 1;

+------------+---------------+
| title      | blog_name     |
+------------+---------------+
| What We Do | chicago_pages | 
+------------+---------------+
1 row in set (0.00 sec)

但是在 Rails 控制台中,这是我得到的:

>> @titles = Title.find_by_sql("select title,blog_name from exp_weblog_titles JOIN exp_weblogs ON exp_weblog_titles.weblog_id = exp_weblogs.weblog_id LIMIT 1")
=> [#<Title title: "What We Do">]

我已经看到了这样一个事实,即出于某种原因,Rails 只会在控制台模式下显示第一个表中的列,而没有一点技巧。谁能告诉我如何访问连接的属性?

【问题讨论】:

    标签: mysql ruby-on-rails activerecord


    【解决方案1】:

    我不完全确定您对连接属性的含义。不过,我猜你需要的是这样的:

    class Title < ActiveRecord::Base
       belongs_to :weblog
    end
    
    class Weblogs < ActiveRecord::Base
       has_many :titles
    end
    

    您可以通过以下方式获取博客的标题属性

    @weblog = Weblog.find(...) 
    @webglog.title.attributes 
    

    另一方面

    @titles = Title.find_all
    @titles[0].weblog.attributes
    

    希望有帮助

    【讨论】:

      【解决方案2】:

      如果你不想重构现有的表,可以让 Rails 符合。

      使用此类 AR 模型:

      class Title < ActiveRecord::Base
        set_table_name "exp_weblog_titles" 
      
        belongs_to :weblog, :foreign_key => 'weblog_id' # foreign_key not even needed here
      end
      
      class Weblog < ActiveRecord::Base
        set_table_name "exp_weblogs"
        set_primary_key "weblog_id"
      
        has_one :title, :foreign_key => 'weblog_id' # or here
      end
      

      这应该可行:

      Weblog.all.each {|w| puts "#{w.title.title} #{w.blog_name}"}
      

      或者使用Title.connection.select_rows('SELECT statement here'),这将返回一个行数组,但是我不明白使用Rails的意义。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多