在铁路应用中按交付区域搜索餐厅(2)

时间:2017-08-14 13:39:48

标签: ruby-on-rails ruby search many-to-many area

我想在rails应用程序的ruby中通过delivery_area搜索餐馆..我创建了一个多对多的关系..在控制台中一切正常,但是当我在搜索表单中选择一个区域时它无法正常工作..我认为我在餐厅控制器中有问题

## restaurant.rb
class Restaurant < ApplicationRecord
 has_and_belongs_to_many :areas
end

## area.rb
class Area < ApplicationRecord
 has_and_belongs_to_many :restaurants
end 

## migration (for rails 5.0)


  class CreateJoinTableAreaRestaurant < ActiveRecord::Migration[5.0]
  def change
    create_join_table :areas, :restaurants do |t|
      # t.index [:area_id, :restaurant_id]
      # t.index [:restaurant_id, :area_id]
    end
  end
end


# in view:
<div class="field">
  <%= f.label :delivery_areas %>
  <%= f.collection_check_boxes :area_ids, Area.all, :id, :name do |b| %>
    <div class="collection-check-box">
      <%= b.check_box %>
      <%= b.label %>
    </div>
  <% end %>
</div>

## restaurants_controller.rb
def index
  @restaurants = Restaurant.all.order("created_at DESC")
  if params[:area].blank? 
    @restaurants = Restaurant.all.order("created_at DESC")
  else 
    @area_id = Area.find_by(name: params[:area]).id 
    @restaurants = Restaurant.where(:area_id => @area_id).order("created_at DESC")
  end 
end

## search form
<ul class="dropdown-menu scrollable-menu" aria-labelledby="dropdownMenu1" style="width: 440px;">
                  <% @areas.each do |area| %>
                    <li>
                      <%= link_to area.name, restaurants_path(area: area.name), class: "link" %>
                    </li>
                  <% end %>
</ul>

1 个答案:

答案 0 :(得分:1)

我认为您的迁移代码不应该在其中定义关系。

From Rails API:

class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
  def change
    create_table :developers_projects, id: false do |t|
      t.integer :developer_id
      t.integer :project_id
    end
  end
end