0

我正在开发一个 Ruby-on-Rails 网络应用程序,它主要用于跟踪产品技术规格。这是我在遵循 Michael Hartl 的 Rails 教程后第一次使用 RoR 应用程序。我对 Ajax 或 RoR 还不是很敏锐,也没有意识到我正在处理如此激烈的事情,但我渴望看到它。

要了解模型关系,请参阅我的 ER 图

我有 3 个模型:

@entity: { :id, :name, :label, :img }
@group: { :id, :name, :default_label }
@property: { :id, :name, :units, :units_short, :default_label, :default_value, :default_visibility }

然后,这些模型中的每一个都有独特的多对多关联(我需要在其中跟踪有关关系的细节),因此我为这些关联创建了模型。

@group_property_relationship: { :group_id, :property_id, :order }
@entity_group_relationship: { :entity_id, :group_id, :order, :label }
@entity_property_relationship: { :entity_id, :property_id, :group_id, :label, :order, :value, :visibility }

我已经让这些模型及其关联相互对话,并且在控制台上运行得非常好。但是设置客户端是复杂的地方。查看我的模型以了解我希望它的外观,希望这将激发对功能的理解。

我正在尝试创建一个一站式视图,其中所有内容都可以使用 ajax 在一个页面上进行管理。用户可以创建实体、属性或组,创建组和属性之间的关联,以及创建实体和组之间的关联。

在此处查看我的进度的静态视图:

https://trello-attachments.s3.amazonaws.com/519e948c97d3fd4579000a79/537fa898eef9844886200be0/463x710/b04e83d4e4e56253a1818048264e1fa3/spex_hub_140617.png

显然,对于更多链接,我没有足够高的 SO 声誉。对于两种模型,搜索、排序和分页都通过 ajax 工作,彼此独立。我遵循了本教程:

http://asciicasts.com/episodes/240-search-sort-paginate-with-ajax

要获得大部分功能,但必须对其进行一些调整以更新 Rails 4 并在一个视图中为多个模型工作。

但是,它不起作用的地方是,当使用“进度”图像顶部附近的表单从该视图创建实体时(成功与否),成功创建实例,更新列表,排序工作,但搜索中断

所以,为了追踪错误,我需要提供大量代码......这里是:

风景: hub

app/views/hub/main.html.erb

<div id="hub-alert"></div>
<div class="row">
    <aside class="col-xs-4 v-divider">
        <a style="color: #494A4A" href="<%= entities_path %>">Entities</a>
        <section>
            <h6>
                Create New Entity
            </h6>
            <%= render 'new_entity' %>
        </section>
        <section>
            <h6>
                Existing Entities
            </h6>
            <%= render partial: 'entities/search', locals: { path: hub_path } %>
            <div id="entities">
                <%= render 'entities/entities' %>
            </div>
            <div id='ajax-test'></div>
        </section>
    </aside>
    <aside class="col-xs-4 v-divider">
        <a style="color: #494A4A" href="<%= groups_path %>">Groups</a>
        <section>
            <h6>
                Selected Entity's Groups
            </h6>
            <div id="entitys_groups"> 
            </div>
        </section>
        <section>
            <h6>
                Create New Group
            </h6>
            <%= render 'groups/new' %>
        </section>
        <section>
            <h6>
                Existing Groups
            </h6>
            <%= render partial: 'groups/search', locals: { path: hub_path } %>
            <div id="groups">
                <%= render 'groups/groups' %>
            </div>
            <div id='ajax-test'></div>
        </section>
    </aside>
</div>

创建实体部分: _create_entity.html.erb

app/views/hub/_create_entity.html.erb

<h1> Create New Entity</h1>

<div class="row">
  <div class="col-xs-10 col-xs-offset-1">
    <%= bootstrap_form_for(@entity, url: { controller: "hub", action: "create_entity" }, inline_errors: false, method: :post, remote: true) do |f| %>
      <%= render 'entities/fields', f: f %>
      <%= f.submit "Create Entity", class: "btn btn-sm btn-primary btn100", id: "create-entity" %>
    <% end %>
  </div>
</div>

实体搜索部分: _search.html.erb

app/views/entities/_search.html.erb

<%= form_tag path, method: 'get', remote: true do %>
    <%= hidden_field_tag :entity_direction, params[:entity_direction] %>
    <%= hidden_field_tag :entity_sort, params[:entity_sort] %>
    <%= hidden_field_tag :entity_event, true %>
    <div class="input-group" style="margin-bottom: 15px">
        <%= text_field_tag :entity_search, params[:entity_search], class: "form-control" %>
        <span class="input-group-btn" >
            <%= submit_tag "Search", name: nil, class: "btn btn-default" %>
        </span>
    </div>
<% end %>

控制器: hub_controller .

app/controllers/hub_controller.rb

class HubController < ApplicationController
  helper_method :entity_sort_column, :entity_sort_direction, :group_sort_column, :group_sort_direction

  before_action do
    unless current_user.nil?
      redirect_to root_url unless current_user.admin?
    else
      redirect_to root_url
    end
  end

  def main
    @entities = Entity.search(params[:entity_search]).order(entity_sort_column + ' ' + entity_sort_direction).paginate(page: params[:entities_page], per_page: 10, order: 'created_at DESC')
    @groups = Group.search(params[:group_search]).order(group_sort_column + ' ' + group_sort_direction).paginate(page: params[:groups_page], per_page: 10, order: 'created_at DESC')
    @entity = Entity.new
    @group = Group.new
  end

  def create_entity
    @entity = Entity.find_by(name: entity_params[:name])
    @result = {msg: "", r: -1}
    @entities = Entity.search(params[:entity_search]).order(entity_sort_column + ' ' + entity_sort_direction).paginate(page: params[:entities_page], per_page: 10, order: 'created_at DESC')

    respond_to do |format|
      if @entity.nil?
        @entity = Entity.new(entity_params)
        if !@entity.save
          @result[:r] = 0
          @result[:msg] = "'#{@entity.name}' failed to save."
        else
          @result[:r] = 1
          @result[:msg] = "'#{@entity.name}' was saved."
          #entities needs to be updated to get the latest addition
          @entities = Entity.search(params[:entity_search]).order(entity_sort_column + ' ' + entity_sort_direction).paginate(page: params[:entities_page], per_page: 10, order: 'created_at DESC')
        end
      else
        @result[:r] = 0
        @result[:msg] = "Name: '#{@entity.name}' is already taken."
      end
      format.js
      format.html { redirect_to hub_path }
    end
  end

  def create_group
    #not yet implemented
  end

  def create_property
    #not yet implemented
  end

  def create_entity_group_relation
    #not yet implemented
  end

  def create_group_property_relation
    #not yet implemented
  end

  private

    def entity_params
      params.require(:entity).permit(:name, :label, :img)
    end

    def group_params
      params.require(:group).permit(:name, :default_label)
    end

    def entity_sort_column
      Entity.column_names.include?(params[:entity_sort]) ? params[:entity_sort] : "name"
    end

    def entity_sort_direction
      %w[asc desc].include?(params[:entity_direction]) ? params[:entity_direction] : "asc"
    end

    def group_sort_column
      Group.column_names.include?(params[:group_sort]) ? params[:group_sort] : "name"
    end

    def group_sort_direction
      %w[asc desc].include?(params[:group_direction]) ? params[:group_direction] : "asc"
    end

end

路线: routes.rb

Spex::Application.routes.draw do
  get "hub/main"
  post "hub/create_entity"
  post "hub/create_group"
  post "hub/create_property"
  post "hub/create_entity_group_relation"
  post "hub/create_group_property_relation"
  get "groups/new"
  get "entities/new"
  get "entities/hub"
  get "properties/new"
  resources :users
  resources :group_property_relationships
  resources :entity_group_relationships
  resources :entity_property_relationships
  resources :properties do
    member do
      get :groups, :entities
      post :serve
    end  
  end
  resources :groups do
    member do
      get :properties, :entities
      post :own
    end  
  end
  resources :entities do
    member do
      get :groups, :properties
      post :own
    end  
  end

  resources :sessions, only: [:new, :create, :destroy]
  root 'static_pages#home'
  match '/hub/create_entity', to: 'hub#main',   via: 'get'
  match '/signup',  to: 'users#new',            via: 'get'
  match '/hub',     to: 'hub#main',             via: 'get'
  match '/signin',  to: 'sessions#new',         via: 'get'
  match '/signout', to: 'sessions#destroy',     via: 'delete'
  match '/help',    to: 'static_pages#help',    via: 'get'
end

ajaxizesapplication.js排序和其他一些基本功能——<em>这里没有 create 调用:

/app/assets/javascripts/application.js

$(function()
{

    $('#entities').on('click', "th a", function () {
        $.getScript(this.href);
        return false;
    });

    $('#groups').on('click', "th a", function () {
        $.getScript(this.href);
        return false;
    });

    $("body").on("click", '.pagination a', function(e){
      e.preventDefault();
      $.getScript(this.href);
      return false;
    });

    $("body").on("click", '.table tr.entity', function(e){
      // e.preventDefault();
      $.getScript(this.id+"/groups");
      // return false;
    });

    $("[data-toggle='tooltip']").tooltip();

});

这是该create_entity操作的回调 js:

app/views/hub/create_entity.js.erb

var entities_html = "  <%= j render 'entities/entities' %>";

$('#entities').html(entities_html)

//clear the entity form fields
$('input[id^=entity]').val('');

var alert_html = "";

<% unless @result.nil? %>
    <% if @result[:r] == 1 %>
        alert_html += "    <div class='alert alert-success'>";
        alert_html += "    <%= @result[:msg] %>";
        alert_html += "    </div>";
    <% else %>
        alert_html += "    <div class='alert alert-danger'>";
        alert_html += "        <%= @result[:msg] %>";
        alert_html += "    </div>";
    <% end %>
<% else %>
    alert_html += "    <div class='alert alert-danger'>";
    alert_html += "        There was an error saving #{@entity.name}";
    alert_html += "    </div>";
<% end %>

$('#hub-alert').html(alert_html);

所以在这一点上,路线或其他东西发生了一些奇怪的事情。create_entity我可以看到在调用之前和之后服务器打印的内容发生了变化。主要注意参数的变化。他们为什么要改变?

前:

Started GET "/hub?utf8=%E2%9C%93&entity_direction=&entity_sort=&entity_event=true&entity_search=o+v" for 127.0.0.1 at 2014-06-17 14:48:13 -0600
Processing by HubController#main as JS
  Parameters: {"utf8"=>"✓", "entity_direction"=>"", "entity_sort"=>"", "entity_event"=>"true", "entity_search"=>"o v"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'e39061f2d24bec8416f5319586f87f27def3804c' LIMIT 1
DEPRECATION WARNING: #apply_finder_options is deprecated. (called from main at /Users/astoutj/Documents/Work/_sync/Work-sync/ror/workspace/spex/app/controllers/hub_controller.rb:13)
DEPRECATION WARNING: #apply_finder_options is deprecated. (called from main at /Users/astoutj/Documents/Work/_sync/Work-sync/ror/workspace/spex/app/controllers/hub_controller.rb:14)
  Entity Load (0.5ms)  SELECT "entities".* FROM "entities" WHERE ((name LIKE '%o%' OR label LIKE '%o%' OR created_at LIKE '%o%' OR updated_at LIKE '%o%') AND (name LIKE '%v%' OR label LIKE '%v%' OR created_at LIKE '%v%' OR updated_at LIKE '%v%')) ORDER BY name asc, created_at DESC LIMIT 10 OFFSET 0
  Rendered entities/_entity.html.erb (1.5ms)
  Rendered entities/_entities.html.erb (8.0ms)
  Group Load (0.4ms)  SELECT "groups".* FROM "groups" ORDER BY name asc, created_at DESC LIMIT 10 OFFSET 0
   (0.1ms)  SELECT COUNT(*) FROM "groups"
  Rendered groups/_group.html.erb (10.4ms)
  Rendered groups/_groups.html.erb (19.2ms)
  Rendered entities/_entity.html.erb (1.2ms)
  Rendered entities/_entities.html.erb (6.3ms)
  Rendered hub/main.js.erb (45.5ms)
Completed 200 OK in 53ms (Views: 49.3ms | ActiveRecord: 1.2ms)

后:

Started GET "/hub?utf8=%E2%9C%93&entity_direction=&entity_sort=&entity_event=&entity_search=o+v" for 127.0.0.1 at 2014-06-17 14:48:33 -0600
Processing by HubController#main as JS
  Parameters: {"utf8"=>"✓", "entity_direction"=>"", "entity_sort"=>"", "entity_event"=>"", "entity_search"=>"o v"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'e39061f2d24bec8416f5319586f87f27def3804c' LIMIT 1
DEPRECATION WARNING: #apply_finder_options is deprecated. (called from main at /Users/astoutj/Documents/Work/_sync/Work-sync/ror/workspace/spex/app/controllers/hub_controller.rb:13)
DEPRECATION WARNING: #apply_finder_options is deprecated. (called from main at /Users/astoutj/Documents/Work/_sync/Work-sync/ror/workspace/spex/app/controllers/hub_controller.rb:14)
  Group Load (0.4ms)  SELECT "groups".* FROM "groups" ORDER BY name asc, created_at DESC LIMIT 10 OFFSET 0
   (0.1ms)  SELECT COUNT(*) FROM "groups"
  Rendered groups/_group.html.erb (6.0ms)
  Rendered groups/_groups.html.erb (14.8ms)
  Entity Load (0.7ms)  SELECT "entities".* FROM "entities" WHERE ((name LIKE '%o%' OR label LIKE '%o%' OR created_at LIKE '%o%' OR updated_at LIKE '%o%') AND (name LIKE '%v%' OR label LIKE '%v%' OR created_at LIKE '%v%' OR updated_at LIKE '%v%')) ORDER BY name asc, created_at DESC LIMIT 10 OFFSET 0
  Rendered entities/_entity.html.erb (2.1ms)
  Rendered entities/_entities.html.erb (12.8ms)
  Rendered hub/main.js.erb (35.7ms)
Completed 200 OK in 44ms (Views: 39.4ms | ActiveRecord: 1.5ms)

问题:如何让创建操作不干扰后续搜索操作?

让我知道是否需要其他任何东西。

4

1 回答 1

0

好的,这就是我必须做的。

我也有一个main.js.erbwhich 将是该main操作的回调。在那里,我无意中通过检查参数阻止了对我的部分的更改。我正在检查的参数是entity_eventgroup_event对于相应模型的任何操作都是正确的(即排序、搜索、页面、新建)。所以我在搜索字段中添加了一个参数,params[:search]当搜索为 a 时entityparams[:search]设置为"entity",当搜索为 a 时group,它设置为"group"。这是更新的文件。

搜索实体

app/views/hub/_search_entity.html.erb

<%= form_tag path, method: 'get', url: { controller: "hub", action: "main" }, remote: true do %>
    <%= hidden_field_tag :entity_direction, params[:entity_direction] %>
    <%= hidden_field_tag :entity_sort, params[:entity_sort] %>
    <%= hidden_field_tag :entity_event, true %>
    <%= hidden_field_tag :search, "entity" %>
    <div class="input-group" style="margin-bottom: 15px">
        <%= text_field_tag :entity_search, params[:entity_search], class: "form-control", id: "entity_search_field" %>
        <span class="input-group-btn" >
            <%= submit_tag "Search", name: nil, class: "btn btn-default", id: "entity_search" %>
        </span>
    </div>
<% end %>

搜索组

app/views/hub/_search_group.html.erb

<%= form_tag path, method: 'get', url: { controller: "hub", action: "main" }, remote: true do %>
    <%= hidden_field_tag :group_direction, params[:group_direction] %>
    <%= hidden_field_tag :group_sort, params[:group_sort] %>
    <%= hidden_field_tag :group_event, true %>
    <%= hidden_field_tag :search, "group" %>
    <div class="input-group" style="margin-bottom: 15px">
        <%= text_field_tag :group_search, params[:group_search], class: "form-control", id: "group_search_field" %>
        <span class="input-group-btn" >
            <%= submit_tag "Search", name: nil, class: "btn btn-default", id: "group_search" %>
        </span>
    </div>
<% end %>

主要动作回调

app/views/hub/main.js.erb

<% unless params[:search] == "entity" %>
    $('#groups').html('<%= j render "groups/groups"  %>');
    console.log("entity event empty");
<% end %>

<% unless params[:search] == "group" %>
    $('#entities').html('<%= j render "entities/entities"  %>');
    console.log("group event empty");
<% end %>

现在它在创建操作之前和之后完全响应。

于 2014-06-18T14:58:10.607 回答