【问题标题】:ActiveRecord creating new objects every time I load the index.erb每次加载 index.erb 时 ActiveRecord 都会创建新对象
【发布时间】:2014-11-12 03:01:18
【问题描述】:

我正在使用 Sinatra 和 ActiveRecord 创建一个简单的 wiki 网站。我遇到一个问题,每次我尝试为特定文档的版本加载索引视图时,都会创建一个新版本。我查看了我的路线和我的版本模型,但似乎无法弄清楚,尽管它可能很明显(我是初学者)。任何帮助,将不胜感激 :) 部分相关代码:

VERSIONS_CONTROLLER.rb

# ===============
#    Versions
# ===============

# INDEX

get '/documents/:document_id/versions' do 
    @document = Document.find(params[:document_id])
    @versions = Version.where(["document_id = ?", params[:document_id]])
    erb :'versions/index'
end

# NEW
get '/documents/:id/versions/new' do 
    @authors = Author.all()
    @document = Document.find(params[:id])
    erb :'versions/new'
end

# SHOW
get '/documents/:document_id/versions/:id' do 
    # @versions = Version.find(params[:document_id])
    @document=Document.find(params[:document_id])
    @version = Version.find(params[:id])
    erb :'versions/show'
end

# CREATE 
post '/documents/:document_id/versions' do 
    version = Version.new(params[:version])
    document.update(body: version.content)
    version.save
    redirect("/documents/#{ params[:document_id] }")
end

# REVERT

# The revert function is going to post to
# the create function above. It is going to 
# do this via a revert button under each 
# button on the versions/index.erb page.
# When pressed, the button will post a 
# /documents/:document_id/versions form
# with the params[:document_id][:version]
# set to equal those of the version under
# which the button is located

版本/索引.ERB

<div class="versions-index-wrapper">
    <div class="versions-index-header">
        <h1>
            Version history for document: <%= @document.title  %>
        </h1>
    </div>
    <div class="versions-index-list">
            <% @versions.each do |version| %>
                <li>
                    <a href="/documents/<%= @document.id %>/versions/<%= version.id %>">
                    COMMIT: <%= version.blurb %><hr>
                    CREATED AT:<%= version.created_at %><hr>    BY:
                    <%= version.author.username %><hr>
                    </a>
                </li>
            <% end %> 
    </div>
</div>.

版本型号

class Version < ActiveRecord::Base
    belongs_to :document
    belongs_to :author
    has_many :comments, dependent: :destroy

    def self.latest
        self.order("created_at DESC")
    end

end

架构

DROP TABLE IF EXISTS comments CASCADE;
DROP TABLE IF EXISTS versions CASCADE;
DROP TABLE IF EXISTS documents CASCADE;
DROP TABLE IF EXISTS authors;

CREATE TABLE authors (
    id SERIAL PRIMARY KEY,
    first_name VARCHAR(255),
    last_name VARCHAR(255),
    username VARCHAR(255),
    points INTEGER,
    icon_url VARCHAR(255),
    github_url VARCHAR(255),
    twitter_url VARCHAR(255)
);

CREATE TABLE documents (
    id SERIAL PRIMARY KEY,
    title VARCHAR(255),
    img_url VARCHAR(255),
    created_at TIMESTAMP,
    updated_at TIMESTAMP,
    author_id INTEGER,
    body TEXT
);

CREATE TABLE versions (
    id SERIAL PRIMARY KEY,
    blurb TEXT,
    content TEXT,
    created_at TIMESTAMP,
    document_id INTEGER references documents,
    author_id INTEGER references authors
);

CREATE TABLE comments (
    id SERIAL PRIMARY KEY,
    created_at TIMESTAMP,
    version_id INTEGER references versions,
    author_id INTEGER references authors,
    content VARCHAR(512)
);

DOCUMENTS.rb

class Document < ActiveRecord::Base
    has_many :versions, dependent: :destroy
    has_many :authors, through: :versions
    after_initialize :init

    def init
        last_updated = Time.now.utc.iso8601.gsub('-', '').gsub(':', '')
         self.versions << Version.create({ 
             content: "version 1.0",
             blurb: "v1.0",
             author_id: Author.first.id
             })
    end

    def self.latest
        self.order("updated_at DESC")
    end

    def self.alphabetical
        self.order("title ASC")
    end

end

【问题讨论】:

  • 创建新对象是什么意思?你的意思是它正在创建新的表条目?这真的很奇怪,因为我没有看到在 index.html 中调用任何创建或保存方法。如果您的意思是每次在浏览器中访问 /documents/:document_id/versions 路径,那么我认为这并不意外,您每次发出请求时都需要初始化对象,对吧。
  • 如何创建版本,Document 上的回调?
  • 文档对象可能有答案。可以发一下吗?
  • @JaimeBellmyer 我已经更新了 document.rb ..也许它与我的 init 类方法有关?

标签: ruby activerecord sinatra


【解决方案1】:

after_initialize 回调运行每次一个 ActiveRecord 对象被加载到 Rails 中。由于您的应用会在每次请求时加载文档,因此每次都会调用您的 init 方法,从而生成一个新版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-24
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多