简体   繁体   中英

ActiveRecord creating new objects every time I load the index.erb

I'm working on creating a simple wiki website using Sinatra and ActiveRecord. I'm having a problem where every time I try to load the index view for versions of a specific document, A new version is being created. I've taken a look at my routes and my Version model, but just can't seem to figure it out, although it is probably something glaring (I'm a beginner). Any help would be appreciated :) Some of the relevant code:

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

VERSIONS/INDEX.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>.

VERSIONS MODEL

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

SCHEMA

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

The after_initialize callback runs every time an ActiveRecord object is loaded into Rails. Since your app is loading the document on every request, your init method is being called every time, generating a new version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM