I want to search restaurants by delivey_area in a ruby on rails app.. I created a Many-to-Many Relationship.. In console everything is working but when i select an area in my search form it is not working.. I think i have something wrong in restaurants controller
## 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>
I think your migration code is not suppose to have relationship defined in it.
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