表格未正确提交

时间:2015-10-08 14:57:25

标签: ruby-on-rails ruby forms

我有一个Rails应用程序,显示用户附近的餐馆推荐。

有一个Posts#index页面,其中显示了所有Restaurant个,而每个Restaurant都有不同的参数。我最感兴趣的是Zagat_status

当用户点击Zagat_status复选框时,我想要更新Posts#index视图,以便它只显示Restaurant的段落zagat_status = "Yes"

我的档案如下。我怀疑问题出在我的索引文件中。我缺少什么/如何让它工作?

视图/帖/ index.html.erb

<div class="main-wrap">
  <div class="map-side-bar">
    <div class="search-filter">
      <form>
        <span>Accolades</span>
        <div class="accolades-panel">

          <label>
            Zagat<dd>rated</dd><input type="checkbox" name="zagat_status" value="Yes">
          </label>

        </div>
      </form>
    </div>
  </div>
</div>

模型/ post.rb

class Post < ActiveRecord::Base

  scope :zagat_status, -> (zagat_status) { where zagat_status: zagat_status }

  validates :name, presence: true
  validates :city, presence: true
  validates :address, presence: true

  def self.search(query)
    where("name like ? OR city like ? OR address like ?", "%#{query}%", "%#{query}%", "%#{query}%")
  end
end

控制器/ posts_controller.rb

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

1 个答案:

答案 0 :(得分:0)

<强> index.html.erb

<div class="main-wrap">
  <div class="map-side-bar">
    <div class="search-filter">
      <form id="my_form">
        <span>Accolades</span>
        <div class="accolades-panel">

          <label>
            Zagat<dd>rated</dd><input id="zagat_status" type="checkbox" name="zagat_status" value="Yes">
          </label>

        </div>
      </form>
    </div>
  </div>
</div>

<强> index.js

function sendData() {
    $.post( "<your post url here>",{'zagat_status':$('#zagat_status'.val()})
    .done(function(data) {
       alert('Success!');
    });
}

$(document).ready(function() {
    $('#zagat_status').change(function() { 
         sendData(); 
    });
});

将jQuery lib和index.js导入index.html.erb