I have a search form on my page with two buttons - "news" and "events".
I can get the Rails search function to work correctly but I don't want a search form, I want the user to press one of the two buttons and the search to be executed.
I figure this probably has to be done with JQuery so when a button is clicked, either "news" or "events" are added to the rails input form and it submits the form. Please appreciate where I'm going wrong here as the form won't submit and the search won't execute.
Application.js
$(document).on('ready page:load', function () {
$(".news-button").click(function(){
$("#search").val("news");
$("#news-search").submit();
});
$(".events-button").click(function(){
$("#search").val("event");
$("#news-search").submit();
});
});
Index.html.erb
<%= form_tag news_index_path, :method => 'get', :id => "news_search" do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<div class="col-sm-3 sort-buttons">
<%= link_to "News", "", class: "btn btn-standard news-button" %>
<%= link_to "Events", "", class: "btn btn-standard events-button" %>
</div>
<div class="row">
<% #news.each do |n| %>
<div class="col-sm-4">
<div class="news-wrap">
<%= image_tag("#{n.image}", class: "img-responsive", alt: "Event/News Postings") %>
</div>
</div>
<% end %>
</div>
News.rb
class News < ApplicationRecord
if Rails.env.development?
def self.search(search)
if search
where('category LIKE ?', "%#{search}%")
else
scoped
end
end
end
end
News Controller:
def index
if params[:search]
#news = News.search(params[:search]).page(params[:page]).per_page(10)
else
#news = News.all.page(params[:page]).per_page(10)
end
end
Related
I'm building a Rails app in which there are exercises and user_answers. When the user sees an exercise, there is a form that he can submit with the answer he thinks is right.
When submitting, I want the same view to be shown, without a refresh, but with a new div which has the solution of the exercise. The view shown is the exercises/show and a form rendered in the user_answers folder. Right now, my code looks like this:
exercises/show.html.erb
<div class="container exercise-page">
<h2 class="exercise-title">ExercĂcio <%= #exercise.id %> de <%= #exercise.category %> - <%= #exercise.sub_category %></h2>
<br>
<%= render 'user_answers/user_answer_form' %>
<br>
<div id="solution_exercise">
</div>
user_answers/_user_answer_form.html.erb
<%= simple_form_for [#exercise, #user_answer], authenticity_token: true, remote:true, :method => 'POST', :html=> { class: 'col-xs-12 col-sm-12 col-lg-3 mx-auto text-center list-group', id:"form"} do |f| %>
<%= f.simple_fields_for :answers, include_id: false do |answer| %>
<%= f.input_field :answer,
label: 'Answer',
as: :radio_buttons,
class: 'form-check-input',
:item_label_class => 'list-group-item',
name: 'answer',
collection: #answers, label_method: :answer %>
<br>
<%= f.submit 'Submit Answer!', class: "btn btn-outline-success", id: "submit" %>
<% end %>
user_answers_controller.rb
def create
#user_answer = UserAnswer.new(user_answer_params)
#answers = Exercise.find(params[:exercise_id]).answers
#exercise = Exercise.find(params[:exercise_id])
#user_answer.exercise = #exercise
#user_answer.answer = #exercise.answers.find(params[:answer])
#user_answer.user_id = current_user.id
#user_answer.save
respond_to do |format|
format.js
end
end
user_answers/create.js.erb
solution = document.querySelector("solution_exercise")
solution.innerHTML = '<%= j render partial: "solution" %>'
user_answers/_solution.html.erb
<p>Your answer: <%=current_user.user_answers.last.answer.answer%></p>
The error:
Does someone know what I'm doing wrong?
A bit of a confusing title.
I am trying to implement a bit of a reddit like comment system. So that you can view a Post and add a Comment to it which is polymorphic. Or, comment on another Comment.
My view looks like so:
<h2>Post:</h2>
<div class="well">
<p>
<strong>Title:</strong>
<%= #post.title %>
</p>
<% if #post.description %>
<p>
<strong>Description:</strong>
<%= #post.description %>
</p>
<% end %>
</div>
<% if current_user %>
<%= render "shared/comment_form" %>
<% else %>
<p>Log in to add comments</p>
<% end %>
<% if #post.comments.any? %>
<%= render "shared/comment_list" %> # Another comment_form inside of this partial
<% else %>
<p>No comments yet</p>
<% end %>
Inside of comment_list is another rendering of comment_form so that you can comment on a comment:
<h2>Comments</h2>
<ul>
<% #post.comments.each do |co| %>
<li><%= co.body %></li>
<%= render "shared/comment_form" if current_user %>
<% end %>
</ul>
Finally, my comment form itself:
<div id="comment-form" class="form-group">
<%= form_for #comment, remote: true, url: post_comments_path(#post) do |f| %>
<%= f.text_area :body, required: true, rows: 5, class: "form-control" %>
<%= f.hidden_field :commentable_id, :value => #post.id %>
<%= f.hidden_field :commentable_type, :value => #post.class.name %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<br>
<%= f.submit class: "btn btn-primary" %>
<% end %>
</div>
<span id="add-comment">Add a comment</span>
And the Jquery code that acts on the comment_form:
$(document).on('turbolinks:load', function() {
$("#comment-form").hide();
$('#add-comment').click( function() {
$("#comment-form").fadeToggle("fast");
($("#add-comment").text() === "Cancel") ? $("#add-comment").text("Add comment") : $("#add-comment").text("Hide");
});
});
My question is:
How could I separate these divs so that Jquery doesn't fire on all instances of id="comment-form? I would like to pass in an erb tag like <%= #post.class.name %><%= #post.id %>, but again, keep the variable universal. Then, how could I implement that unique id name in my JQuery code.
Edit: I got one part of my question solved. I left the rest of what I wasn't able to do up for everyone to see.
You could use prev() like this:
$(document).ready(function() {
$('.comment-form').hide();
$('.add-comment').click( function(event) {
// Store the button which has just been clicked on a variable
var eventTarget = $(event.target);
// Find the previous element with the #comment-form and id and toggle it
eventTarget.prev('.comment-form').fadeToggle('fast');
// Use the eventTarget Again
(eventTarget.text() === 'Cancel') ? eventTarget.text('Add comment') : eventTarget.text('Cancel');
});
});
You can see this in action here: http://codepen.io/rebagliatte/pen/MbKNJv
My application contains a very simple login and two separate AJAX calls. I have a loading spinner that is hidden automatically whenever a page is ready it is contained in index.js
$(function() {
$("loading").hide();
$("#scan_button").on("ajax:success", function(e, data, status, xhr) {
$("#standard_results").hide();
$("#results").show();
$("#results").html(data);
});
$(document).ajaxStop(function() {
$("#loading").hide();
});
$(document).ajaxStart(function() {
$('#loading').show();
});
});
When a user logs in the following happens
class SessionController < ApplicationController
def create
user = User.find_by(username: params[:session][:username])
if(user.password == params[:session][:password])
log_in user
redirect_to root_path
end
end
def destroy
logout
redirect_to root_path
end
end
The route path takes me back to 'home#index' for which the index.js file exists. When the user logs in the redirect happens and the loading spinner is hidden and all JavaScript executes as expected.
When the user hits log out however the redirect occurs, but the loading spinner is shown and no JavaScript ever gets executed. Here is my index.html.erb file that contains the JavaScript.
<% content_for :title, "Network Monitor" %>
<div class="container-fluid">
<nav class="navbar narvbar-dark bg-inverse">
<span class="navbar-brand">Network Monitor</span>
<%= link_to "Scan", scan_path, remote: true, class: "btn btn-secondary", id: "scan_button" %>
<% if logged_in? %>
<span class="pull-xs-right"><%= link_to "Logout", logout_path, class: "btn btn-secondary" %></span>
<% else %>
<%= form_for(:session, url: login_path, :html => {:class => 'form-inline pull-xs-right'}) do |f| %>
<%= f.text_field :username, class: 'form-control', placeholder: "Username" %>
<%= f.password_field :password, class: 'form-control', placeholder: "Password" %>
<%= f.submit "Log in", class: 'btn btn-primary', id: 'login_button' %>
<% end %>
<% end %>
</nav>
<div id="loading">
<%= image_tag "loading.gif", class: "loading_gif" %>
</div>
<div class="row">
<div class="col-md-12">
<div id="scan_bar">
<h3>Welcome to your network monitor!</h3> <br />
<p>To get started hit the scan button in the top right corner, this will detect the computers that are alive on your network and show them below.</p>
</div>
</div>
</div>
<div class="row">
<div id="results">
</div>
<div id="standard_results">
</div>
Solved. It was as simple as using
$(document).on('turbolinks:load', function() {});
Instead of what I had posted, this seems to be the way that Rails 5 and turbolinks want you to use, and it worked.
According to the
turbolinks document, I use the event page:change to solve the problem:
$(document).on("page:change", function(){...});
It works for me.
In case others run into this. If you are using an href or link_to try doing something like this:
<li><%= link_to "Home", jobs_path, method: :get %></li>
...where you specify the get method in the request.
Hi guys I really need help here.
I'm making a todo app and displaying each task through an iteration. Next to each task I have a pencil glyphicon.
When I click on it, I want there to be a popover containing an edit form and edit the task on the spot. I'm having a ton of troubling rendering that form.
***** UPDATE *****
Clark helped me get the popover to work. But The form inside the popover is acting like a link instead of a form so I can't type in the text area.
This is my index.html.erb
<div id='user_tasks'>
<% #tasks.each do |task| %>
<ul>
<li>
<%= task.description %>
<%= link_to edit_task_path(task), :rel => 'popover', method: 'get', remote: 'true' do %>
<span class = 'edit_task_<%=task.id%> glyphicon glyphicon-pencil'> </span>
<% end %>
</li>
</ul>
<% end %>
</div>
This is the edit.js.erb
$(function(){
$('.edit_task_<%=#task.id%>').popover({
html: true,
title: 'edit',
content: <%= escape_javascript render 'edit_form', task:#task %>
}).popover('show'); });
and my controllers look like this:
def index
#new_task= Task.new
#tasks= Task.all
end
def create
#new_task= Task.new(task_params)
#task.save
redirect_to :back
end
def edit
#task= Task.find(params[:id])
end
_edit_form.html.erb looks like this: This isn't the edit form that I plan to use. Its just a copy of the create task form. I plan to fix it once I get the popover working.
<%= form_for task, :html=>{:class=> 'form-inline'} do |f| %>
<div class='form-group'>
<%= f.text_field :description, placeholder: 'create a task' %>
<%= button_tag(type:'submit', class:"btn btn-default btn-xs") do %>
<span class='glyphicon glyphicon-plus'></span>
<% end %>
</div>
<% end %>
I have a _user.html.erb partial that I am rendering on my Users#Index action with a form embedded to allow following and unfollowing of each user. I also have accompanying create.js.erb and destroy.js.erb files in my relationships controller to handle the AJAX. Right now I have to refresh the page in order to see the changes made by clicking the "follow/unfollow" button next to a users name except the first user's record behaves correctly.
_user.html.erb
<div id ="follow_form">
<% if current_user.following?(user) %>
<%= form_for(current_user.relationships.find_by(followed_id: user.id),
html: { method: :delete },
remote: true) do |f| %>
<%= f.submit "Unfollow", class: "btn btn-large" %>
<% end %>
<% else %>
<%= form_for(current_user.relationships.build(followed_id: user.id),
remote: true) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>
<% end %>
create.js.erb
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").html('<%= #user.followers.count %>')
destroy.js.erb
$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>")
$("#followers").html('<%= #user.followers.count %>')
here is a link to my users_controller.rb https://gist.github.com/anonymous/9608208 and my relationships_controller.rb https://gist.github.com/anonymous/9608284
I've tried changing the div to something dynamic like
<div id ="follow_form_<%= user.id %>">
But when I make the same change to the javascript like this
$("#follow_form_<%= user.id %>").find.html("<%= escape_javascript(render('users/unfollow')) %>")
it doesn't seem to work.
I've been trying to figure out how to pass the user.id attribute into the javascript but am falling flat.
It turns out the problem was in my _follow_form.html.erb partial.
I had to change
<div id="follow_form">
to
<div id="follow_form_<%= #user.id %>">
I thought I only needed to make the change in the _user.html.erb partial but I was wrong. My current user partial uses the same div id to contain the button in the Users#Index view
<div id ="follow_form_<%= user.id %>">