Ruby on rails - 如何计算并返回要显示的值

时间:2017-11-15 05:55:08

标签: ruby-on-rails

我是铁杆新手。我有基本的下来。我想要做的是当有人点击“生成”时,它将从数据库中的大型列表中获取一个标题和一个描述,执行50次,然后在新页面上显示这些。

我不太确定这是怎么做的。这个逻辑是在控制器中处理还是这是一个rake任务?

我有多快(我也设置了所有视图):

路线:

Rails.application.routes.draw do
  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
  devise_for :users
  root to: "home#index"

  resources :articles
end

型号:

  create_table "articles", force: :cascade do |t|
    t.text     "title"
    t.text     "body"
    t.text     "keywords"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "name"
  end

控制器:

class ArticlesController < ApplicationController
  before_action :authenticate_user!
  before_action :find_article, only: [:edit, :update, :show, :destroy]

  def index
    @articles = Article.all
  end
  # Creates article
  def new
    @article = Article.new
  end
  # Saves article
  def create
    @article = Article.new(article_params)
    if @article.save(article_params)
      flash[:notice] = "Successfully created #{@article.title}"
      redirect_to article_path(@article)
    else
      flash[:alert] = "Error creating #{@article.title}"
      render :new
    end
  end
  # renders edit page
  def edit

  end
  #updates article with new info
  def update
    if @article.update_attributes(article_params)
      flash[:notice] = "Successfully updated article!"
      redirect_to article_path(@article)
    else
      flash[:alert] = "Error updating article!"
      render :edit
    end
  end

  # renders the article
  def show
  end

  # deletes the article
  def destroy
    @article = Article.find(params[:id])
    if @article.destroy
      flash[:notice] = "Successfully deleted!"
      redirect_to articles_path
    else
      flash[:alert] = "Error deleting article"
    end
  end

  private

  def article_params
    params.require(:article).permit(:title,:body,:keywords,:name)
  end

  def find_article
    @article = Article.find(params[:id])
  end
end

1 个答案:

答案 0 :(得分:1)

generate或其他地方添加index.html.erb按钮。

index.html.erb

link_to "Generate", foo_articles_path, class: "some-class"

的routes.rb

resources :articles do
  get :foo, on: :collection
end

然后将foo方法/操作添加到文章控制器

def foo
  @articles = Article.take(50) #or some other constraints
end

如果你想在不同的视图中渲染它们(例如foo.html.erb),请在app/views/articles路径下创建一个。如果您将其命名为foo以外的其他名称(例如bar.html.erb),则应明确将其包含在foo操作中。

def foo
  @articles = Article.take(50)
  render :bar 
end

在该视图中,根据需要渲染@articles