I have a Rails app which shows a list of restaurants with different parameters. I'm trying to add a filter through a checkbox so that if user checks the checkbox, the view only shows those posts where the restaurants is Zagat rated.
My code is below. Why isn't it working?
POSTS INDEX FILE (INDEX.HTML.ERB)
<script type="javascript">
function sendData() {
$.post( "index",{'zagat_status':$('#zagat_status'.val("")})
.done(function(data) {
alert('Success!');
});
}
$(document).ready(function() {
$('#zagat_status').change(function() {
sendData();
});
});
</script>
<label> Zagat<dd>rated</dd><input type="checkbox" name="zagat_status" value="Yes">
</label>
POSTS CONTROLLER
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
# GET /posts
# GET /posts.json
def index
@posts = Post.all
if params[:search]
@posts = @posts.search(params[:search]).order("created_at DESC")
end
if params[:zagat_status].present?
@posts = @posts.zagat_status(params[:zagat_status]).order("created_at DESC")
end
end
POSTS MODEL
scope :zagat_status, -> (zagat_status) { where zagat_status: zagat_status }
Are you sure you're getting the right value for the checkbox? If you put the line
raise params.to_s
at the start of your index function, is it sending the params you want? That would help determine if the issue is on the javascript side (most likely) or on the rails server side.
I recently ran into a similar issue where calling $('#zagat_status').val()
did not give me the value I want. Try using the snippet below, where you call ($(this).is(':checked'))
to see if the checkbox is checked and pass it to your controller.
$('#zagat_status').change(function(){
var isChecked = ($(this).is(':checked'))
$.post( "index",{'zagat_status': isChecked })
.done(function(data) {
alert('Success!');
});
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.