Changing hyperlink on refresh - javascript

How to put just one random link(out of many) on page every time a user reloads the page?
e.g
link 1
link 2
...
or in rails
<%= link_to "link 1", "https://google.com" %>
...

just use some rand value, for example
/*view.html.erb*/
<% var ||= rand(2) %>
<%= link_to_if var == 0, "http://www.google.com" %>
<%= link_to_if var == 1, "http://www.facebook.com" %>
you can set this into a partial, or maybe an array in your controller a call the array with de rand value like
<%= link_to #array_of_links[var] %>
or if you want to save this into your db you can just pick a random record with
/*controller*/
#link = Link.order("RANDOM()").first
because of MVC flow it will get a random value each time, regards

Related

Nested url queries in ruby on rails

I'm making this choose your own adventure page and I'm using form_tag to accept user input. At the start of this page a user will enter a number through this text field
<% choice_1a = "1" %>
<% choice_1b = "2" %>
<%= form_tag("/pathfinder/quest1", method: "get") do %>
<center><%= text_field_tag(:a, #input_1, maxlength: 1) %>
<%= submit_tag("Submit") %></center>
<% end %>
<% input_1 = #input_1 %>
<% if input_1 == choice_1a %>
**Run code if user entered 1 **
<%= form_tag("/pathfinder/quest1", method: "get") do %>
<center><%= text_field_tag(:b, #input_2, maxlength: 1) %>
<%= submit_tag("Submit") %></center>
<% end %>
<% elsif input_1 == choice_1b %>
**Run code if user entered 2 **
<% else %>
** Prompt user to enter a 1 or 2**
<% end %>
Which results in this output in the url of the query "a" equaling whatever input was given. In this case I entered one ("&a=1")
https://192.168.0.200:3000/pathfinder/quest1?utf8=checkmark symbol&a=1&commit=Submit
After that path is taken they are given another form_tag that shown as below
Path if 1 was chosen at form_tag "a"
<%= form_tag("/pathfinder/quest1", method: "get") do %>
<center><%= text_field_tag(:b, #input_2, maxlength: 1) %>
<%= submit_tag("Submit") %></center>
<% end %>
When they enter a number here the url would change to this. Note how "a" was replaced with "b".
https://192.168.0.200:3000/pathfinder/quest1?utf8=checkmark symbol&b=1&commit=Submit
I was hoping to somehow nest these queries so that if a=1 I can have the user set the input to "b" it would still reflect their previous input to "a"
Here's a partial of the show section of the pathfinder controller that this code is running off
Controller code
if url == ('/pathfinder/quest1')
if params[:a].present?
#input_1 = "#{params[:a]}"
elsif params[:b].present?
#input_2 = "#{params[:b]}"
end
render 'quest1/index'
What I'm trying to do is give the user the option to set a=1 and then under that branch allow b to set 1 or 2. An example of what I'm trying to accomplish
a=1 (being one path) or a=2(being the other path)
| |
V V
b=1 <---> b=2 c=1 <-----> c=2
**Different paths if the user were to set "a" to one or two**
If the user set "a" equal to one, they would have the option of setting "b" to one or two. The same concept would be for "a" equal to two where the user would only have the option of setting "c" to one or two.
I'm open to any other ideas that doesn't require changing the url if its through html, css or javascript

Rails - refreshing page with new table entries

The goal I am trying to achieve is to let the user click on a button which will refresh to page filter that search. My page is dedicated to music artists and would like that once the user selects "Pop", that the page refreshes showing only "pop" artists.
Here is the html + ruby that I am using to display the artists:
<% #prints the artists that match the search, prints all for empty search %>
<% #artists.each_slice(3) do |artists| %>
<div class="row">
<% artists.each do |artist| %>
<div class = "artist_images">
<%= link_to image_tag(artist.artist_art, class: 'show_image'), artist_path(artist) %><br/><br/>
</div>
<% end %>
</div>
<% end %>
<% #prints message showing that the search does not match %>
<% if !#artists.present? %>
<h3><center style = "color: white">There are no artists containing the term(s) "<%= params[:search] %>". Please try 'Adele', 'Drake', 'Kanye West', or 'Taylor Swift'</center></h3>
<% end %>
The controller has the following methods:
def index
#artists = Artist.all
end
def randomPop
#artists = Artist.where(:genre => "\nPop").random(9)
end
Does anyone know how I can go about changing the variable #artists from All artists to those in pop only through a button click?
in your view,
<%= button_to "Pop", artists_path, method: :get, params: { artist_genre: "Pop" } %>
in your controller,
def index
if params[:artist_genre]
#artists = Artist.where(:genre => params[:artist_genre]).random(9)
else
#artists = Artist.all
end
end
This classic railscast episode is on point. I would use that for how you set up your search box. The only thing you might alter/update:
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
Should probably be a where clause based on your situation"
if search
where("genre = ?", your_genre)
else
all
end

How to return a selected value from a database collection in Rails?

So I have a database collection labeled #joe, and I am trying to pass the id variable into a link url path. This is in my index.erb.html file.
<%= select_tag "article", options_from_collection_for_select(#joe, 'id', 'title'),
prompt: "Select Something" %>
In my articles_controller.rb file, I have
def index
#joe = Article.all
end
I made a loop where it grabs each id number and passes it into the article_url path. I was wondering, in the dropdown box that I created above, when I select a certain value, I want to pass that value into the article.id variable. I'm having trouble with this and it outputs x amount of buttons.
<% #joe.each do |article| %>
<%= button_to "SELECT", article_url(article.id), :method => 'get' %>
<% end %>
I was wondering if it is possible to do this or if I can implement JavaScript or jQuery into this. Any help would be appreciated. Thank you!
And here's the rake routes command results:
Prefix Verb URI Pattern Controller#Action
home_index GET /home/index(.:format) home#index
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
root GET / home#index
Let's try this:
ERB
<%= form_tag article_path do %>
<%= select_tag "id", options_from_collection_for_select(#joe, 'id', 'title'), prompt: "Select Something", class: 'select' %>
<%= button_tag 'SELECT', class: 'button' %>
<% end %>
JS
$('.button').on('click', function() {
var path = $('form').attr('action');
var articleId = $('.select').val();
$.get([path, articleId].join('/'));
});

how to make collection_select value as link_to variable

I have the ff:
app/views/reports/index.html.erb
<h1>Reports</h1>
<br>
<legend>Categories</legend>
<div class="row">
<div class="span5">
<ol>
<li><%= link_to 'COMMENDATION', commendations_path(format: 'pdf'), { id: 'commendations_click' } %></li>
<%= collection_select(nil,
:employee_id,
#employees,
:id,
:last_name,
{:prompt => "Select an Employee"},
{:id => 'employees_select'}) %>
<br>
<%= collection_select(nil,
:employee_movement_id,
#employeemovements,
:id,
:position,
{:prompt => "-"},
{:id => 'employee_movements_select'}) %>
<li><%= link_to 'REPORT2', '#' %></li>
<li><%= link_to 'REPORT3', '#' %></li>
</ol>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#employees_select').change(function() {
$.ajax({
url: "<%= update_employee_movements_path %>",
data: { employee_id : $('#employees_select').val() },
dataType: "script"
});
});
$('#commendations_click').click(function() {
$.ajax({
url: "<%= commendations_path %>",
data: {
employee_id : $('#employees_select').val(),
employee_movement_id : $('#employee_movements_select').val()
},
dataType: "script"
});
});
});
</script>
app/controllers/reports_controller
class ReportsController < ApplicationController
before_filter :authenticate_user!
# GET /reports
def index
#employees = Employee.all
#employeemovements = EmployeeMovement.distinct_positions
end
def update_employee_movements
if params[:employee_id]
#employeemovements = [].insert(0, "Select Employee Movement")
else
employee = Employee.find(params[:employee_id])
#employeemovements = employee.employee_movements.map{ |a| [a.position, a.id] }.insert(0, "Select Employee Movement")
end
end
def commendations
emdates = EmployeeMovement.last_2_dates_obtained(params[:employee_movement_id])
date_from = emdates[0].date_obtained
date_to = emdates.length == 1 ? nil : emdates[1].date_obtained
emp = Employee.find(params[:employee_id])
#commendations = case date_to.nil?
when true then emp.commendations.this_day_onwards(date_from)
else emp.commendations.within(date_from, date_to)
end
end
end
What I'm trying to do here is, I'm creating a page filled with links and drop down lists that will serve as a Reports center. The idea is, each link will be catered by a controller. Each controller will be responsible in showing my PDF in the browser (through ThinReports, if you're curious).
The #employees_select change event is used for changing the value of the #employee_movements_select collection_select.
Now my problem is, how can i capture the value of both #employees_select and #employee_movements_select and pass them to my commendations action?
I tested link_to by hardcoding values, and it works (code below)
<%= link_to 'COMMENDATION', commendations_path(employee_id: 1, employee_movement_id: 12, format: 'pdf') %>
However, If I use javascript to push the values to my commendations action through the 'click' event, my commendations action will be called twice, thus an error occurs because the params[:employee_id] in the action is now blank.
By the way, I need those values because my commendations action needs it so I can populate my PDF report template.
Please help. Thanks a lot in advance!
UPDATE 1
-> Updated link_to:
<%= link_to 'COMMENDATION', '#', { id: 'commendations_click' } %>
-> Removed dataType: "script" in #commendations_click event handler
-> Updated url: in #commendations_click event handler
url: <%= commendations_path(format: 'pdf') %>
UPDATE 2 (RESOLUTION)
I tweaked my javascript to look something like this:
$('#commendations_click').click(function() {
event.preventdefault();
window.location = "<%=j commendations_path(format: 'pdf') %>" + "?employee_id=" + $('#employees_select').val() + "&employee_movement_id=" + $('#employee_movements_select').val();
});
Works perfect now.
Two things come to mind. You can wrap the two select lists within a form element and just do a submit. Everything inside the form will be submitted to your server and you can process the request and handle the redirect on the server side. The other thing you can do is to handle the commendations click event on the client side using jquery or something. Just bind to the click event of that link, grab the values of the two select lists and do whatever you want with it. Remember, link_to just gets rendered as plain old html links on the view. For e.g.
link_to "Profile", profile_path(#profile) gets rendered as Profile

How can I send an automatically generated ID for a form element to a javascript function?

I am trying to call a javascript function from my form page in a Rails 3 project. I need to send the function the ID of a particular element. Unfortunately I can't get the ID easily since it is automatically generated by a plugin.
I tried doing it this way:
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(' + the_value.id.to_s + "');"} %>
<% if (!the_value.nil?) && (!the_value.number_type.nil?) && !#id_types_sm.include? the_value.number_type) %>
<script type="text/javascript">
setup_other_field("<%= the_value.number_type %>", ###ID WOULD GO HERE###);
</script>
<% end %>
.. But since I don't know the ID of the element, I can't call it from the function.
So now I'm trying to do it this way, by calling the function from an "onload" when the input element loads:
<% if (!the_value.nil?) && (!the_value.number_type.nil?) && (!#id_types_sm.include? the_value.number_type) %>
<%# Call the function from the form helper only if the conditions are met %>
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(this.id);", :onload => "setup_other_field('" + the_value.number_type + "', this.id);"} %>
<% else %>
<%# Use the form helper without calling the function %>
<%= t.select :number_type, #id_types, {}, {:onchange => "has_other_field(this.id);"} %>
<% end %>
BUT I realize that onload does not work for this situation. Is there any workaround for this? How can I either
A) get the element ID from the field to the function in the first option, or
B) call this function from this input element whenever it loads?
... or C) an alternative way to do this?
Thanks in advance and let me know if more details would help.
If you have ID saved in the model, get it with <%= model.id %>
Exception to this rule is when you create object, and it is before it is written to database. If you go to edit or anywhere else it will be ok.
If you have it somewhere on the page :/ then you can use jQuery to get it for you.
< div id="id_of_the_element" attr_with_my_id="15" >ABC< /div >
$("#id_of_the_element").attr('attr_with_my_id')
< input id="id_of_the_element ... >< /input >
$("#id_of_the_element").value

Categories

Resources