Reputation: 137
In controller
if params[:name]==params[:name]
@categories=Category.where(:hotel_id=>params[:hotel_id])
@menus=Menu.where(:category_id=> params[:id]).sorted
@cart = current_cart
end
In index page:
<%@categories.each do |d|%>
<%= link_to d.name ,{:action=>'index',:id=>d.id,:hotel_id=>d.hotel_id},class: "btn-orange" %>
<%end%>
I am getting all the categories and it's respected menu items from database. how do i automatically click the first category link when page loads.
Upvotes: 1
Views: 549
Reputation: 5112
use each_with_index to get/detect the first element(this is what you want) and then click it using jquery
view file
<%@categories.each_with_index do |d,index|%>
<%= link_to d.name ,{:action=>'index',:id=>d.id,:hotel_id=>d.hotel_id},id:first_"#{index}",class: "btn-orange" %>
<%end%>
====================js code to click when page is ready============
$(document).ready(function(){
setTimeout(function() {
//click after 2 seconds when page loads or remove it or use=> $('#first_0').trigger('click'); directly without setTimeout in document.ready()
$("#first_0").click();
}, 2000);
})//document ends
Upvotes: 0
Reputation: 76784
To answer your question bluntly, you'll have to use JQuery to invoke the click event:
#app/assets/javascripts/application.js
var loaded = function(){
$("a.first_link").trigger("click");
};
$(document).on("page:load ready", loaded);
--
Structure
Needless to say, this does not mean you'll be making a robust, efficient system. Instead, it means you'll be calling an event which you shouldn't need to.
As mentioned in the comments, it looks like your controller is the place where this type of business logic should occur:
#config/routes.rb
resources :hotels do
resources :categories
end
#app/models/hotel.rb
class Hotel < ActiveRecord::Base
has_many :categories
end
#app/models/category.rb
class Category < ActiveRecord::Base
has_many :menus
end
#app/controllers/categories_controller.rb
class CategoriesController < ApplicationController
before_action :set_cart
def index
@hotel = Hotel.find params[:hotel_id]
@categories = @hotel.categories
@menus = @categories.find(params[:id]).menus.sorted
end
private
def set_cart
@cart = current_cart
end
end
Upvotes: 2
Reputation: 3046
You can use trigger
to call action on jquery, as the following:
$(documnet).on("page:load ready", function(){
$("a.first_link").trigger("click");
})
You can read more trigger, and load page event.
Upvotes: 0