Not showing posts where boolean is true - javascript

I have an app I am making where users can post items and then they can select "live" when they select "live" as true the post should show up in a live tab.
Right now this is my posts_controller.rb create and update actions
def create
#post = Post.new(post_params)
if #post.save
redirect_to post_path(#post)
flash[:success]="Post created"
else
render 'new'
end
end
def update
#post = Post.find(params[:id])
if #post.update(post_params)
flash[:success]="Updated successfully"
redirect_to post_path(#post)
else
render 'edit'
end
end
--------------------------------
def post_params
params.require(:post).permit(:title, :description,
:category_id, :subcategory_id, :live)
end
My Post form for editing and creating a new post.
<script type="text/javascript">
$(document).ready(function() {
var subcat;
subcat = $('#subcategory-select').html();
return $('#category-select').change(function() {
var cat, options;
cat = jQuery('#category-select').children('option').filter(':selected').text();
options = $(subcat).filter("optgroup[label='" + cat + "']").html();
if (options) {
return $('#subcategory-select').html(options);
} else {
return $('#subcategory-select').empty();
}
});
});
</script>
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
<%= render 'shared/errors', obj: #post%>
<%= form_for #post do |f| %>
<p>
<%= f.label :title %><br/>
<%= f.text_field :title, maxlength: "10" %>
</p>
<p>
<%= f.label :description %><br>
<%= f.text_area :description %>
</p>
<p>
<%= f.label :category_id%>
<%= f.collection_select(:category_id, Category.all, :id, :name,
{ prompt: 'Select a category' }, { id: 'category-select' }) %>
</p>
<p>
<%= f.label :subcategory_id%>
<%= f.grouped_collection_select :subcategory_id, Category.all, :sub_categories,
:name, :id, :name, { include_blank: 'Select a sub category' },
{ id: 'subcategory-select' } %>
</p>
<p>
<%= f.label :live%>
<%= check_box_tag :live , 0 , #post.live ? false : true %> <!--work on-->
<p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to "Back to posts listing", posts_path %>
The posts doesn't save as being live, I can force it into being live with the rails console however. This brings me to the next issue.
I forced a post to have live == true and it doesn't show up in my bootstrap live tab. This is for my subcategory show action which is where I am trying to do this first.
def show
#subcategory = SubCategory.find(params[:id])
#subcategory_posts = #subcategory.posts#live posts in this subcat
#subcategory_posts_live = (params[:live] == 'true')
end
And the show.html.erb bootstrap navigation tabs which should show the live posts but doesn't on click
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">Posts</li>
<li role="presentation">Live ◯</li>
<li role="presentation">xx</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="home"><%=render 'posts/post', obj: #subcategory_posts %></div>
<div role="tabpanel" class="tab-pane" id="profile"><%=render 'posts/post', obj: #subcategory_posts_live %></div>
<div role="tabpanel" class="tab-pane" id="messages">...</div>
</div>
I know that it is looking for posts because in the view it shows <p>No Listings found</p> which is what I am displaying in my 'posts/_post` partial if no posts are found within that specific category i.e Live Subcategory Posts.
Unsure on how to work this one out, any guidance appreciated.

It looks like your form is missing a checkbox to allow the user to select if a post is live or not. You need a checkbox.
So something like this may work:
<%= f.check_box :live %>
To query for all posts that are live (I'm assuming this is a boolean column in your db):
#live_posts = Post.where(live: true)
For your subcategory query, you can do this:
#subcategory_posts = Post.where(subcategory_id: params[:id], live: true)
(This assumes posts have a subcategory_id column)

Related

rails - Update View when Form is Submitted without Refreshing the Page

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?

JQuery Input Rails Form

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

Rails 5: Trying to render divs with a single partial but keep the div class unique so that JQuery doesn't fire on all partials

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

Rendering a partial to an edit form inside a popover in rails 4

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 %>

Rails showing series of objects with form_for and Ajax

I'm trying to show a list of "Interests" that users can "follow" by clicking on a button associated with the Interest's image. Upon clicking the button to follow an Interest, the Interest (and it's corresponding image) should disappear from the list.
I'm using a hide function in a create.js.erb file called upon by a Relationship controller when the follow button is clicked, but the function will only hide the first Interest in the series of Interests--NOT the Interest the user clicked on that needs to disappear. So there has to be a better way to set this up, but I cannot, for the life of me, figure it out. Here's my current setup:
My Controller
class StaticPagesController < ApplicationController
def home
#user = current_user
#city = request.location.city
#interests = Interest.all
end
The home page
<%= render #interests %>
The partial
<div id="follow_form">
<div class="four columns portfolio-item interests">
<div class="our-work">
<a class="img-overlay">
<%= image_tag interest.image_path %>
<div class="img-overlay-div">
<h4><%= interest.name %></h4>
</br>
<h5>Placeholder
</br>
<%= interest.desc %></h5>
<%= form_for(current_user.relationships.build(followed_id:
interest.id), remote: true) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "I'm interested", class: "b-black" %>
<% end %>
</div>
</a>
<h3><%= interest.name %><span>features info</span></h3>
</div>
</div>
</div>
And the create.js.erb that's called upon by a Relationships controller when you click the button:
$("#follow_form").hide();
UPDATE
Here is the Relationships controller for additional clarification
def create
#interest = Interest.find(params[:relationship][:followed_id])
current_user.follow!(#interest)
respond_to do |format|
format.html { redirect_to(root_url) }
format.js
end
end
You need to provide something to differentiate the different "follow_forms" that you have on the same page. Otherwise, jQuery will just select the first element and only remove that one.
One idea of how to do this would be to append the "interest.id" to the end of the follow_form id
Update your partial to be like this (assuming your partial is called and located in /app/views/interests/_follow_form.html.erb:
<div id="follow_form<%="#{interest.id} %>">
<div class="four columns portfolio-item interests">
<div class="our-work">
<a class="img-overlay">
<%= image_tag interest.image_path %>
<div class="img-overlay-div">
<h4><%= interest.name %></h4>
</br>
<h5>Placeholder
</br>
<%= interest.desc %></h5>
<%= form_for(current_user.relationships.build(followed_id:
interest.id), remote: true) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "I'm interested", class: "b-black" %>
<% end %>
</div>
</a>
<h3><%= interest.name %><span>features info</span></h3>
</div>
</div>
</div>
This way each follow_form will have a unique ID attached to it. Then you can loop through your interests and call a partial on each one like this:
home page:
<% #interests.each do |interest| %>
<%= render 'interests/follow_form', :interest => interest %>
<% end %>
create.js.erb
$("#follow_form_<%= "#{#interest.id}" %>").hide())
Your controller action can stay the same.

Categories