如何创建读钢轨的型号,没有支持表 [英] How to create read only models in rails with no backing table

查看:99
本文介绍了如何创建读钢轨的型号,没有支持表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建读,可能是一些复杂的结果只会车型 加入或汇总查询,有一点就任何直接表模型类 我已经定义了。

I would like to create read only models that may be the result of some complex join or aggregate query that has little relation to any of the direct table model classes I have defined.

例如虚的ActiveRecord :: View类

For example the imaginary ActiveRecord::View class

class B < ActiveRecord::View
    default_scope do
        find_by_sql <<-EOF
            select x.alpha alpha, y.a_id a_id from
            x.join y on x.id = y.id
        EOF     
    end

    belongs_to :a
end

class A < ActiveRecord::Base
    has_many :b
end

>> a = A.first
>> puts a.id

10

>> puts a.bs.to_sql

select x.alpha alpha, y.a_id a_id from
x.join y on x.id = y.id
where a_id = 10

我相信上述或类似的东西是有的,但我无法找到它。

I am sure the above or something like it is available but I just can't find it.

推荐答案

我已经发布了Ruby的创业板,解决了这个问题。

I've released a Ruby GEM that solves this problem

https://github.com/bradphelan/Active-Illusion

该规范文件验证行为

require 'rubygems'
require 'active_illusion'
require 'squeel'

TIMES = (ENV['N'] || 10000).to_i

require 'rubygems'
require "active_record"

conn = { :adapter => 'sqlite3', :database => ':memory:' }
ActiveRecord::Base.establish_connection(conn)

class User < ActiveRecord::Base
    connection.create_table :users, :force => true do |t|
        t.string :name, :email
        t.timestamps
    end

    has_many :exhibits
end

class Exhibit < ActiveRecord::Base
    connection.create_table :exhibits, :force => true do |t|
        t.belongs_to :user
        t.string :name
        t.text :notes
        t.integer :ssn
        t.timestamps
    end

    belongs_to :user

    def look; attributes end
    def feel; look; user.name end

    def self.look(exhibits) exhibits.each { |e| e.look } end
    def self.feel(exhibits) exhibits.each { |e| e.feel } end
end

module ActiveRecord
    class Faker
        LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non aliquet diam. Curabitur vel urna metus, quis malesuada elit. Integer consequat tincidunt felis. Etiam non erat dolor. Vivamus imperdiet nibh sit amet diam eleifend id posuere diam malesuada. Mauris at accumsan sem. Donec id lorem neque. Fusce erat lorem, ornare eu congue vitae, malesuada quis neque. Maecenas vel urna a velit pretium fermentum. Donec tortor enim, tempor venenatis egestas a, tempor sed ipsum. Ut arcu justo, faucibus non imperdiet ac, interdum at diam. Pellentesque ipsum enim, venenatis ut iaculis vitae, varius vitae sem. Sed rutrum quam ac elit euismod bibendum. Donec ultricies ultricies magna, at lacinia libero mollis aliquam. Sed ac arcu in tortor elementum tincidunt vel interdum sem. Curabitur eget erat arcu. Praesent eget eros leo. Nam magna enim, sollicitudin vehicula scelerisque in, vulputate ut libero. Praesent varius tincidunt commodo".split
        def self.name
            LOREM.grep(/^\w*$/).sort_by { rand }.first(2).join ' '
        end

        def self.email
            LOREM.grep(/^\w*$/).sort_by { rand }.first(2).join('@') + ".com"
        end
    end
end

class Test0 < ActiveRecord::Illusion
  column :name
  column :exhibition
  column :number
  #belongs_to :user, :foreign_key => :name

  view do
    User.joins{exhibits}.select{
      [users.name.as(name), exhibits.name.as(xname), exhibits.ssn.as(number) ]
    }
  end
end

# pre-compute the insert statements and fake data compilation,
# so the benchmarks below show the actual runtime for the execute
# method, minus the setup steps

# Using the same paragraph for all exhibits because it is very slow
# to generate unique paragraphs for all exhibits.
notes = ActiveRecord::Faker::LOREM.join ' '
today = Date.today


describe ActiveRecord::Illusion do
    before :each do

        User.destroy_all

        Exhibit.destroy_all

        puts 'Inserting 100 users and exhibits...'
        100.times do |i|
            user = User.create(
                :created_at => today,
                :name       => ActiveRecord::Faker.name,
                :email      => ActiveRecord::Faker.email
            )

            Exhibit.create(
                :created_at => today,
                :name       => ActiveRecord::Faker.name,
                :user       => user,
                :notes      => notes,
                :ssn        => i
            )
        end

    end

    it "should have 100 users" do
        User.count.should == 100
    end

    it "should have 100 exhibits" do
        Exhibit.count.should == 100
    end

    describe Test0 do
        it "should retrieve 100 rows" do
            Test0.where{}.to_sql.should ==
            %Q[SELECT \"test0s\".* FROM (SELECT \"users\".\"name\" AS name, \"exhibits\".\"name\" AS xname, \"exhibits\".\"ssn\" AS number FROM \"users\" INNER JOIN \"exhibits\" ON \"exhibits\".\"user_id\" = \"users\".\"id\") test0s ]
            Test0.count.should == 100


            Test0.where{number < 20}.to_sql.should ==
              %Q[SELECT "test0s".* FROM (SELECT "users"."name" AS name, "exhibits"."name" AS xname, "exhibits"."ssn" AS number FROM "users" INNER JOIN "exhibits" ON "exhibits"."user_id" = "users"."id") test0s  WHERE "test0s"."number" < 20]
            Test0.where{number < 20}.count.should == 20
        end
    end
end

这篇关于如何创建读钢轨的型号,没有支持表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆