【问题标题】:My rails form is not working with has_scope我的 rails 表单不适用于 has_scope
【发布时间】:2016-03-28 14:32:47
【问题描述】:

(我已经编写了不到一个月的代码,如果这是一个愚蠢的问题,我深表歉意)。我有一个只有姓名、电子邮件和类型的用户模型。我创建了一个索引表单,您可以按类型过滤它并显示结果。 表单和过滤器按预期显示我有 2 个问题: 1.用户类型重复。例如,如果我有 5 个用户(使用 faker gem 创建),每个用户都是客户或供应商,过滤器会显示客户和供应商 5 次而不是两次 2.当我选择一个过滤器时,它会显示所有结果,并且它们没有被过滤。

这是我的模型:

class User < ActiveRecord::Base
has_many :microposts
scope :by_userType, ->  userType { where(:userType => userType) }

这是我的控制器

    class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]
  has_scope :by_userType, type: :array #, :using => [:userType]


  # GET /users
  # GET /users.json
  #def index
  #  @users = User.all
  #end

  def index
    @users = apply_scopes(User).all
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/new
  def new
    @user = User.new
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:name, :email, :userType)
    end
end

这是我的表格:

<p id="notice"><%= notice %></p>

<h1>Listing Users</h1>


<%= form_tag users_path, method: 'get', id: "users_search" do%>
<% @users = User.all %>
<% @users.each do |user|%>
<%= check_box_tag "by_userType[]", user.userType %><%= user.userType %><br>
<% end %>
<%= submit_tag "submit" %>
<% end %>

<div id="users"><%= render 'user_list' %></div>

<script type="text/javascript">
  $(function () {
    $('input[type=checkbox]').change(function(){
      $.get($('#users_search').attr('action'),
      $('#users_search').serialize(), null, 'script');
      return false;
    });

  $('users_search').submit(function() {
    $.get(this.action, $(this).serialize(), null, 'script');
    return false;
    });
  });

</script>

提前感谢您的宝贵时间!

【问题讨论】:

  • 您能否向我们展示更多您的观点?例如 user_list 部分?

标签: javascript ruby-on-rails forms


【解决方案1】:

这里有几件事。首先,欢迎使用 rails,也欢迎使用 Stack Overflow。

+1 用于提出问题并为您迄今为止所做的工作提供代码示例。

请注意,对于标准化,大小写在 Rails 中很重要。对于范围的声明,您应该使用蛇形案例。 UserModel 是类名,user_model 是蛇形。

现在就实际实施而言,我会采取不同的做法。如果您注意到大多数基于字段的模型的 ajax 过滤不使用与参数相同的模型,这不是唯一的方式,但我更喜欢它,因为它允许稍后向 user_type 添加额外字段的灵活性。这意味着,如果您将用户类型提取到它自己的模型中,那么您可以轻松地从:name 的 user_type 属性中过滤您的用户。

所以你的用户模型应该有:

class User < ActiveRecord::Base
  has_many :microposts
  belongs_to :user_type
  scope :by_user_type, ->  user_type { where(:user_type => user_type) }
end

然后创建一个名为 user_model 的新模型

rails g scaffold user_model name:string slug:string avatar:string

** 请注意,附加字段只是示例,名称只是必要的一个。但是如果你想让用户做 url 搜索,slug 很容易使用。即 yoursite.com/user_type/sellers

现在创建一个迁移以删除用户中现有的 userType 字段并为关系创建一个新字段。

rails g migration modify_user_type_in_user

那个文件的内容是

class ModifyUserTypeInUser < ActiveRecord::Migration
  def change
    remove_column :users, :userType
    add_reference :users, :user_type, index: true
  end
end

现在编辑新的user_type.rb 模型并添加users 的关系

class UserType < ActiveRecord::Base
  has_many :users 
end

你还需要使用你在帖子中没有提到的 UJS。单击您的表单字段时,它会发送一个 javascript (ajax) 请求。这意味着要更改数​​据,您需要一个 javascript 响应模板。

所以添加文件app/views/users/index.js.erb 并将这些内容放入其中:

$("#users").html('<%= j(render("user_list", users: @users)) %>');
$("table tbody tr:nth-of-type(even)").css("background","#BD9FB1");

最后,您需要更改表单,使其代表正确的可搜索模型。所以编辑'app/views/users/index.html.erb'

<p id="notice"><%= notice %></p>

<h1>User Filter</h1>

<%= form_tag users_path, method: 'get', id: "users_search" do%>
<% @user_types = UserType.all %>
<% @user_types.each do |user_type|%>
<%= check_box_tag "by_user_type[]", user_type.id %><%= user_type.name %><br>
<% end %>
<%= submit_tag "submit" %>
<% end %>

<div id="users"><%= render 'user_list' %></div>

<script type="text/javascript">
  $(function () {
    $('input[type=checkbox]').change(function(){
      $.get($('#users_search').attr('action'),
      $('#users_search').serialize(), null, 'script');
      return false;
    });

  $('users_search').submit(function(e) {
    e.preventDefault();
    $.get(this.action, $(this).serialize(), null, 'script');
    return false;
    });
  });

</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多