如何在一个视图上对数据进行分类

时间:2014-10-12 17:34:46

标签: ruby-on-rails categories

我正在构建一个具有语言模型,问题模型和答案模型的应用程序。我想在一个“我的问题”索引视图页面上显示问题和答案列表,分为以下几类:

  1. 我未回答的问题(仅指属于当前用户的问题)
  2. 我的回答问题(仅指属于当前用户的问题)
  3. 我回答的问题(仅表示属于当前用户的答案)
  4. 我是编程新手,我不确定在Rails中研究“类别”这个词是否适合这个词,但我无法通过这种方式找到任何有用的信息。任何见解都将非常感谢!

    以下是我的路线:

    Languagecheck::Application.routes.draw do
      devise_for :users
      resources :users
    
      resources :languages do
        resources :questions, except: [:index] do 
          resources :answers
        end
       end
    
      resources :questions, only: [:index, :new, :create]
    
      get 'about' => 'welcome#about'
      root to: 'welcome#index' 
      end
    

    这是我的问题模型:

    class Question < ActiveRecord::Base
      require 'obscenity/active_model'
      has_many :answers, dependent: :destroy
      accepts_nested_attributes_for :answers, :reject_if => :all_blank, :allow_destroy=>true
      belongs_to :user
      belongs_to :language
    
      default_scope { order('created_at DESC') }
    
    
      validates :body, obscenity: true
      validates :body, length: { minimum: 10, maximum: 160 }, presence: true
      validates :user, presence: true
    
    end
    

    这是我的答案模型:

      class Answer < ActiveRecord::Base
      require 'obscenity/active_model'
      belongs_to :question
      belongs_to :user
    
     validates :name, obscenity: true
     validates :body, length: { minimum: 1, maximum: 160 }, presence: true
    
    end
    

    我的用户模型已设置,用户有许多问题和答案。

    这是我的问题控制器:

    class QuestionsController < ApplicationController
      before_action :set_language, except: [:index]
      before_action :set_question, only: [:show, :edit, :update, :destroy]
    
      def index
        @questions = current_user.questions
      end
    
      def show
        @question = Question.find(params[:id])
        @answer = Answer.new
      end
    
      def new
        @question = Question.new
        authorize @question
      end
    
      def edit
        @question = Question.find(params[:id])
        authorize @question
      end
    
      def update
         @question = Question.find(params[:id])
         authorize @question
    
         if @question.update_attributes(question_params)
           flash[:notice] = "Question was updated."
           redirect_to [@language, @question]
         else
           flash[:error] = "There was an error saving the question. Please try again."
           render :edit
         end
       end
    
      def create
         @question = Question.new(question_params)
         @question.language = @language
         @question.user = current_user
         authorize @question
    
         if @question.save
           flash[:notice] = "Question was saved."
           redirect_to [@language, @question]
         else
           flash[:error] = "There was an error saving the question. Please try again."
           render :new
         end
       end
      def destroy
        @question.destroy.find(params[:id])
        respond_to do |format|
          format.html { redirect_to questions_url }
          format.json { head :no_content }
        end
      end
    
      private
        def set_question
          @question = Question.find(params[:id])
        end
    
        def question_params
          params.require(:question).permit(:id, :body)
    
        end
    
        def set_language
          @language = Language.find(params[:language_id])
        end
    
    end
    

    这是我的答案控制器:

    class AnswersController < ApplicationController
      before_action :set_language_and_question
      before_action :set_answer, only: [:show, :edit, :update, :destroy]
    
      def index
        @answers = Answer.all
      end
    
      def show
      end
    
      def new
        @answer = Answer.new
      end
    
      def edit
      end
    
      def create
        @answer = Answer.new(answer_params)
        @answer.question = @question
        @answer.user = current_user
    
        respond_to do |format|
          if @answer.save
            format.html { redirect_to [@language, @question], notice: 'Answer was successfully created.' }
            format.json { render action: 'show', status: :created, location: @answer }
          else
            format.html { redirect_to [@language, @question], error: 'Answer was  not successfully created.' }
            format.json { render json: @answer.errors, status: :unprocessable_entity }
          end
        end
      end
    
      def update
        respond_to do |format|
          if @answer.update(answer_params)
            format.html { redirect_to @answer, notice: 'Answer was successfully updated.' }
            format.json { head :no_content }
          else
            format.html { render action: 'edit' }
            format.json { render json: @answer.errors, status: :unprocessable_entity }
          end
        end
      end
    
      def destroy
        @answer.destroy
        respond_to do |format|
          format.html { redirect_to answers_url }
          format.json { head :no_content }
        end
      end
    
      private
    
        def set_answer
          @answer = Answer.find(params[:id])
          @answer ||= @question.answers.new
        end
    
         def answer_params
          params.require(:answer).permit(:id, :body)
        end
    
        def set_language_and_question
          @language = Language.find(params[:language_id])
          @question = Question.find(params[:question_id])
        end
    end
    

    这是“我的问题”视图(目前仅列出所有问题):

    <div class="row">
      <div class="col-md-8">
          <h3>My Unanswered Questions</h3>
          <% @questions.each do |question| %>
             <div class="media">
               <div class="media-body">
                 <h4 class="media-heading">
          <p><%= question.language ? link_to(question.body, [question.language, question]) : question.body %></p>
                </h4>
                <small>
                   submitted <%= time_ago_in_words(question.created_at) %> ago by <%= question.user.name %> <br/>
                   <%= question.answers.count %> Answers
                 </small>
               </div>
             </div>
          <% end %>
           </div>
           <br/>
           <br/>
         <div class="col-md-4">
          <%= link_to "Ask a New Question", new_question_path, class: 'btn btn-success' %>
      </div>
     </div>
    
     <div class="row">
      <div class="col-md-8">
          <h3>My Answered Questions</h3>
          <% @questions.each do |question| %>
             <div class="media">
               <div class="media-body">
                 <h4 class="media-heading">
          <p><%= question.language ? link_to(question.body, [question.language, question]) : question.body %></p>
                </h4>
                <small>
                   submitted <%= time_ago_in_words(question.created_at) %> ago by <%= question.user.name %> <br/>
                   <%= question.answers.count %> Answers
                 </small>
               </div>
             </div>
          <% end %>
           </div>
     </div>
    
    <div class="row">
      <div class="col-md-8">
          <h3>Questions I Answered</h3>
          <% @questions.each do |question| %>
             <div class="media">
               <div class="media-body">
                 <h4 class="media-heading">
          <p><%= question.language ? link_to(question.body, [question.language, question]) : question.body %></p>
                </h4>
                <small>
                   submitted <%= time_ago_in_words(question.created_at) %> ago by <%= question.user.name %> <br/>
                   <%= question.answers.count %> Answers
                 </small>
               </div>
             </div>
          <% end %>
           </div>
     </div>
    

1 个答案:

答案 0 :(得分:0)

瓦莱丽,

像马特一样,我并不完全确定你的意思&#34;分类&#34;。听起来您希望能够遍历给定页面上的各种问题组。所以像这样:

<% @user.unanswered_questions.each do |question| %>
  ...
<% end %>

<% @user.answered_questions.each do |question| %>
  ...
<% end %>

<% @user.answers.each do |answer| %>
  ...
<% end %>

在一个视图上。

如果这就是你的意思,那么马特的建议听起来就像是正确的。您只需在question.rb上创建范围或方法即可实现此目的。我实际上是在创建以下范围:

scope :answered, ->   { joins(:answers) }
scope :unanswered, -> { where.not(id: joins(:answers).pluck(:id)) }

然后你可以@user.questions.answered@user.questions.unanswered(与上面略有不同,但两者都是一个选项)。第二个有点复杂。基本上,我们通过答案(joins(:answers))获取问题,获取他们的ID(pluck(:id)),然后使用不在该集合中的ID来抓取所有问题(即没有答案的那些问题) )。我认为这是有效的,但我还没有对此进行测试。有关详细信息,请查看AR文档:http://guides.rubyonrails.org/active_record_querying.html

这是你的意思吗?通常在Rails中,如果这样的问题涉及对数据进行分段(或分类),您需要考虑将此功能推送到模型层,在那里它是最抽象的。

另请注意,这些范围也可能是类方法。只要他们返回AR关系,就没有什么大不同,所以他们可以被链接#34;。