如何在没有后备表的 Rails 中创建只读模型

Posted

技术标签:

【中文标题】如何在没有后备表的 Rails 中创建只读模型【英文标题】:How to create read only models in rails with no backing table 【发布时间】:2011-08-01 15:12:42 【问题描述】:

我想创建可能是一些复杂的结果的只读模型 与任何直接表模型类几乎没有关系的连接或聚合查询 我已经定义了。

例如想象中的 ActiveRecord::View 类

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

我确定上述内容或类似内容可用,但我找不到。

【问题讨论】:

【参考方案1】:

我发布了一个 Ruby GEM 来解决这个问题

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.joinsexhibits.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.wherenumber < 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.wherenumber < 20.count.should == 20
        end
    end
end

【讨论】:

【参考方案2】:

B 应该是只读的?您是否尝试过 :readonly 选项?

class A < AR::Base
  has_many :b, :readonly => true
end

其他方式有:

a.bs.readonly

class B < AR::Base

  # after_initialize :readonly! # Mark B as readonly after initializing a new one makes no sense
  after_find :readonly! # Mark B as readonly after finding it
end

【讨论】:

但这并没有像问题中那样设置关联。将某些内容标记为只读只会保护我免于做我不应该做的事情,但不会帮助我做我不能做的事情。

以上是关于如何在没有后备表的 Rails 中创建只读模型的主要内容,如果未能解决你的问题,请参考以下文章

如何在没有 XML(仅限 HTML)的 Rails 中创建脚手架?

如何在实体框架中创建只读实体?

Rails:在父模型的视图中创建一个 has_one 模型?

如何在 ActiveRecords 中创建对 Ruby 中对象的引用?

如何在 Python 中创建只读类属性? [复制]

如何在rails 4中创建新的belongs_to关联模型