Есть 2 модели Brands и Category которые объеденные ассоциацией has_and_belongs_to_many
models/brand.rb
class Brand < ActiveRecord::Base
has_and_belongs_to_many :category, :join_table => :brand_catalogs
end
models/category.rb
class Category < ActiveRecord::Base
has_and_belongs_to_many :brands, :join_table => :brand_catalogs
end
миграция
class CreateBrandCatalogs < ActiveRecord::Migration
def change
create_table :brand_catalogs, id: false do |t|
t.belongs_to :category, index: true
t.belongs_to :brand, index: true
end
add_index :brand_catalogs, [:category_id, :brand_id]
end
end
views формы brands
= bootstrap_form_for [@category, @brand] do |f|
div class='form-group'
= f.collection_check_boxes(:category_ids, Category.all, :id, :title)
= f.submit 'Save', class: 'btn btn-success'
Вопрос, как вывести связанные категории в show и index для Brand?
Upd №1
Добавил промежуточную модель
class BrandCatalog < ActiveRecord::Base
belongs_to :category
belongs_to :brand
end
мануал https://robots.thoughtbot.com/rails-has-and-belongs-to-many-conveniences
Upd №2
по мотивам https://stackoverflow.com/questions/17435937/checkbox-for-many-to-many-relationship
Модели brand.rb
class Brand < ActiveRecord::Base
has_many :brand_catalogs
has_many :categories, through: :brand_catalogs
end
category.rb
class Category < ActiveRecord::Base
has_many :brand_catalogs
has_many :brands, through: :brand_catalogs
end
Поправил views
= bootstrap_form_for [:admin, @category, @brand] do |f|
div class='form-group'
= f.collection_check_boxes(:brand, :category_brand_ids, Category.all, :id, :title)
= f.submit 'Save', class: 'btn btn-success'
и контроллер
class Admin::BrandsController < Admin::BaseController
before_action :load_brand, only: [:edit, :update, :destroy]
def index
@brands = Brand.all
end
def new
@brand = Brand.new
end
def edit
end
def create
@brand = Brand.new(brand_params)
if @brand.save
redirect_to admin_brands_path
else
render :new
end
end
def update
if @brand.update(brand_params)
redirect_to admin_brands_path
else
render :edit
end
end
def destroy
if @brand.destroy
redirect_to admin_brands_path
else
end
end
private
def load_brand
@brand = Brand.find(params[:id])
end
def brand_params
params.require(:brand).permit(:title, :content, :seo_title, :seo_keywords, :seo_description, :slug, :published, :logo, category_brand_ids: [])
end
end
CategoryBrand
= @brand.categories
. получаю ошибкуundefined method 'categories'
. в контроллереdef brand_params params.require(:brand).permit(:title, :category_ids ) end