vendredi 26 mai 2017

How to? Rails arrange posts randomly with previous/next view depending on tag_id

So I want to have a link on my rails app which links to a view that shows a random question of a certain tag_id

The use case is a quiz app for my class, and we have N number of tags, with N questions. Each question can have multiple tags.

I want to have a way to be able to randomly display (read: no person should have the same order of questions), but still be able to do all the questions that have a certain tag_id by clicking previous/next in a view.

I figured out how to display all the questions of a certain tag in a view, but I'm still having trouble how to show previous/next randomly for a certain tag. Ex: When a user clicks on a link, it should randomly generate or list all the questions for the tag_id and only be accessible in that view for that tag_id. Everyone will do the same questions, just not in the same order.

I realize there are gems out there, but I want to learn and understand how it's done from scratch first.

questions/show.html.erb

<strong>tags</strong><br>
<%= @question.tags.map{|t| t.name}.join(", ") %>

<%= link_to "Previous Question", @question.previous %>
<%= link_to "Next Question", @question.next %>

Here's my questions_controller.rb

class QuestionsController < ApplicationController

    def new
        @question = Question.new
    end

def index
    if params[:tag_id].present?
        tag = Tag.find(params[:tag_id])
        @questions = tag.questions
    else
        @questions = Question.all
    end
end

    def show
        @question = Question.find(params[:id])  

    end    etc etc ... [rest of code here is redacted as its not relevant]
end

Here's my question.rb model

class Question < ActiveRecord::Base

  has_many :taggings
  has_many :tags, through: :taggings

    #links this to the user.rb model?
    belongs_to :user

    scope :next, lambda {|id| where("id > ?",id).order("id ASC") } # this is the default ordering for AR
    scope :previous, lambda {|id| where("id < ?",id).order("id DESC") }

    def next
      Question.next(self.id).first
    end

    def previous
      Question.previous(self.id).first
    end
end

tag.rb

class Tag < ActiveRecord::Base
    has_many :taggings
    has_many :questions, through: :taggings # notice the use of the plural model name
end

tagging.rb

class Tagging < ActiveRecord::Base
  belongs_to :question  # foreign key - post_id
  belongs_to :tag   # foreign key - tag_id
end




Aucun commentaire:

Enregistrer un commentaire