代码之家  ›  专栏  ›  技术社区  ›  Pistorius

创建嵌套资源的新方法时出错

  •  0
  • Pistorius  · 技术社区  · 7 年前

      resources :flows do
        resources :fmodules
      end
    

    fmodules控制器中的新方法:

    # /flows/1/fmodules/new
    def new
        @flow = Flow.find(params[:flow_id])
        @fmodule = @flow.fmodules.build
    end
    

    模型:

    class Flow < ApplicationRecord
        has_many :fmodules, dependent: :destroy
        validates :code, presence: true, length: { maximum: 5 }
        validates :name, presence: true
    end
    

    class Fmodule < ApplicationRecord
        belongs_to :flow
    end
    

    /flows/1/fmodules/new ruby说 unknown attribute 'flow_id' for Fmodule.

    我不知道怎么了

    此外,这是Fmodel的迁移

    class CreateFmodules < ActiveRecord::Migration[5.1]
      def change
        create_table :fmodules do |t|
          t.string :code
          t.string :name
          t.string :f_code
    
          t.timestamps
        end
        add_foreign_key :fmodules, :flows, column: :f_code
      end
    end
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Nikita Misharin    7 年前

    所以,问题是你没有 flow_id 在你的 fmodules belongs_to 这就是为什么rails认为外键 flows flow\u id 它引发了一个例外,就是找不到它。您可以使用覆盖默认值 foreign_key

    class Fmodule < ApplicationRecord
        belongs_to :flow, foreign_key: : f_code
    end