由具有多个关联的创建操作来分配favorite_category

时间:2019-03-18 03:13:25

标签: ruby-on-rails ruby

问题

我正在尝试创建一个名为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

当我执行创建动作时,我的控制器找不到我的类别。我如何解决它?

我的创建操作从未找到要分配给category_profiles的类别ID。它具有许多直通关系:

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 %>

1 个答案:

答案 0 :(得分:0)

似乎您只想更新中间表。所以你可以这样做。

my_func = lambdify(p, z(p), parameters={'r': 2, 'c': 1})
my_func(2)
Out: 1
z
Out: r/p * (p-c)/(r-c)

需要找到使用事务块或其他方法进行错误处理的其他更好方法。