代码之家  ›  专栏  ›  技术社区  ›  bo-oz

如何处理Rails中特定用例的多对多关系

  •  1
  • bo-oz  · 技术社区  · 6 年前

    我有三种型号:

    class User < ApplicationRecord
      has_many :user_professions
      has_many :professions, through: :user_professions
    
      has_many :interested_professions, -> { where(interested:true) }, class_name: "UserProfession"
    end
    
    class UserProfession < ApplicationRecord
      belongs_to :user
      belongs_to :profession
    end
    
    class Profession < ApplicationRecord
      has_many :user_professions
    end
    

    用户-职业关系是固定的,所以用户有三个关联的职业。这些是不能改变的,是按程序分配的。到目前为止很简单。

    我现在想做的是,使用相同的联接表来管理用户感兴趣的职业列表。我想我应该可以通过同样的关系做到这一点。

    对于这种特定的关系,如果关系已经存在,或者在用户专业表中创建一个新的关系,我需要更新感兴趣的属性。我只知道怎么做表格。

    我试过这个:

    = simple_form_for(@user) do |f|
      - @professions.each do |p|
        = f.simple_fields_for :professions, p do |prof|
          = prof.simple_fields_for :user_professions, @user.user_professions.find_or_initialize_by(profession: p) do |user_prof|
            = user_prof.input :id
            = user_prof.input :interested, as: :boolean, label: s.description
      = f.submit
    

    不过,在尝试提交表单时,Rails会给我一个错误,我真的不明白:

    Couldn't find Profession with ID=1 for User with ID=5
    

    这是正确的,但是在这种情况下Rails应该为它创建一个新的记录。

    有什么想法吗?

    0 回复  |  直到 6 年前