Search code examples
ruby-on-railspostgresqlrandomrecord

Link to random record in header partial (rails)


I'm wondering how to create a "shuffle" button in the header partial of my rails app that links to a random record. I have a "pins" table and each pin is a video.

I've searched through stackoverflow and couldn't figure out how to do it.. I think it had to do with the header partial doesn't work with the Pins controller/model.

When someone clicks the button it should link to something like this:

website.com/pins/13

Any help would be great thanks!

EDIT: This is the code I have previously tried:

offset = rand(Model.count) rand_record = Model.first(:offset => offset)

But I am new to rails and I wasn't sure where to put it. I tried putting it in the model and the controller and both didn't work.


Solution

  • Ok, so I'm assuming that you want a link to a random Model to be shown each time a user loads a particular page. Let's say that the page that shows this link is the ModelController#index action.

    Since the randomization only happens when the page is initially loaded, you can do it in the controller action:

    class ModelController < ActionController::Base
      #other actions
    
      def index
        #any other index code
        @random_model = Model.order('random()').first
      end
    end
    

    Now, in your view, you can link to that model in the usual manner:

    <%= link_to("Shuffle", @random_model, :class => "btn btn-small btn-warning") %>
    

    Every time that the controller action executes, it will pick a Model at random, and include a link to that Model when it renders the page.

    Edited to address: "Is there anyway to make it work without putting the code in the index and show actions?"

    Yes. You can actually load the model right in the view code. Normally, assigning it to an instance variable in the controller is the 'more correct' method, but as you point out, it leads to duplication of code. If this is something you want to include in multiple views, I would recommend making it a partial. Something like so:

    views/shared/_shuffle.erb:

    <%= link_to("Shuffle", Model.order('random()').first, :class => "btn btn-small btn-warning") %>
    

    And then rendering that partial in any page you want to include a randomized link:

    <%= render 'shared/shuffle' %>
    

    Note that if you render this partial more than once in a page, the random model will be different for each link.