我正在尝试创建一个名为category_profiles
的中间表,是一个中间表,为我的配置文件分配喜欢的类别,但我无法访问category_ids
,我放在我的表单中,总是我得到相同的验证,类别没有不存在:
class CategoryProfile < ApplicationRecord
belongs_to :profile
belongs_to :category
end
class Category < ApplicationRecord
has_many :category_profiles
has_many :profiles, through: :category_profiles
class Profile < ApplicationRecord
has_many :category_profiles
has_many :categories, through: :category_profiles
当我在进行创建操作时,我的控制器无法找到我的类别。我如何解决它?
我的创建动作永远不会找到我的类别的ID来分配给category_profiles
。它有很多关系:
Module Account
class FavoritesController < Account::ApplicationController
before_action :set_category_profile
def index
@favorites = @profile.categories
end
def new
@categories = Category.all
@category_profile = CategoryProfile.new
end
def create
@category_profile = @profile.category_profiles.new(category_profile_params)
if @category_profile.save
flash[:success] = t('controller.create.success',
resource: CategoryProfile.model_name.human)
redirect_to account_favorites_url
else
flash[:warning] = @category_profile.errors.full_messages.to_sentence
redirect_to account_favorites_url
end
end
def destroy
end
private
def set_category_profile
@category_profile = CategoryProfile.find_by(params[:id])
end
def category_profile_params
params.permit(:profile_id,
category_ids:[])
end
end
end
<%= bootstrap_form_with(model: @category,method: :post , local: true, html: { novalidate: true, class: 'needs-validation' }) do |f| %>
<div class="form-group">
<%= collection_check_boxes(:category_ids, :id, Category.all.kept.children.order(name: :asc), :id, :name, {}, { :multiple => true} ) do |b| %>
<%= b.label class: 'w-1/6 mr-4' %>
<%= b.check_box class: 'w-1/7 mr-4' %>
<%end %>
</div>
<div class="md:flex justify-center">
<%= f.submit 'Guardar categoría favorita', class: 'btn btn-primary' %>
</div>
<% end %>
好像你只想更新中间表。所以你可以这样做。
def create
begin
@profile.categories << Category.find(params[:category_ids])
Or
params[:category_ids].each do |category_id|
@profile.category_profiles.create(category_id: category_id)
end
flash[:success] = t('controller.create.success',
resource: CategoryProfile.model_name.human)
redirect_to account_favorites_url
rescue
flash[:warning] = @category_profile.errors.full_messages.to_sentence
redirect_to account_favorites_url
end
end
需要找到其他更好的方法来使用事务块或其他东西进行错误处理。