【问题标题】:ActiveRecord::AssociationTypeMismatch Device(#xxxx) expected, got String(#xxxx)ActiveRecord::AssociationTypeMismatch Device(#xxxx) 预期,得到字符串(#xxxx)
【发布时间】:2016-11-28 15:33:57
【问题描述】:

我收到以下错误... ActiveRecord::AssociationTypeMismatch Device(#xxxx) 预期,得到 String(#xxxx)

我无法确定此错误的来源或解决方法。谁能解释我的代码哪里出错了?

模型 =

class Device < ActiveRecord::Base

  has_many :from_links, class_name: "Link", foreign_key: "from_device"
  has_many :to_links, class_name: "Link", foreign_key: "to_device"

  def connected_devices
    from_links.map(&:to_device) + to_links.map(&:from_device)
  end
end

class Link < ActiveRecord::Base

  belongs_to :from_device, class_name: "Device"
  belongs_to :to_device, class_name: "Device"
end

链接控制器 =

class LinksController < ApplicationController
  def create
    @link = Link.new(link_params)
    @device = Device.find_by(en: params[:link][:from_device])
    if @link.save
      flash[:success] = "Link created."
      redirect_to device_path(@device)
    else
      render 'new'
    end
  end

 private

   def link_params
     params.require(:link).permit(:from_device, :to_device, device_attributes: [:en])
   end
end

设备控制器 =

class DevicesController < ApplicationController

  def show
    @device = Device.find(params[:id])
    @linked_devices = @device.connected_devices
  end

private

  def device_params
    params.require(:device).permit(:name, :en, :system_ip, :router_ip, :pop, :chassis_mode, :code_version)
  end

创建链接数据库 =

class CreateLinks < ActiveRecord::Migration[5.0]
  def change
    create_table :links do |t|
      t.references :from_device
      t.references :to_device
    end
  end

创建新的链接表单 =

<% provide(:title, 'New Link') %>
<h1> Create New Link </h1>

<div class="row">
<div class="col-md-6 col-md-offset-3">
  <%= form_for(@link, url: links_path(params[:id])) do |f| %>
    <%= render 'shared/error_messages', object: @link %>

    <%= f.label :from %>
    <%= f.select :from_device, options_for_select(@devices), :include_blank => true, class: 'form-control' %>

    <%= f.label :to %>
    <%= f.select :to_device, options_for_select(@devices), :include_blank => true, class: 'form-control' %>

    <%= f.submit "Submit", class: "btn btn-primary" %>
  <% end %>
</div>

【问题讨论】:

  • 是什么导致了这个错误?我认为它告诉您,抛出错误的任何变量都是一个字符串,并且它需要一个设备 ID。
  • 它说这一行是错误所在.... 提取的源代码(第 8 行附近):def create @link = Link.new(link_params)。它发生在单击提交按钮以保存“创建新链接”的地方。
  • 您也可以在问题中发布您的参数吗?
  • 当然 :) 我在控制器中包含了 link_params 和 device_params

标签: ruby-on-rails database activerecord associations


【解决方案1】:

在链接模型中,您与列 from_deviceto_device 有关联。您想通过任何外键来关联 Links 表。所以像:

has_many :links, foreign_key: "from_device"
has_many :links, foreign_key: "to_device"

看看是否有帮助。您的设备型号也一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 2020-01-06
    相关资源
    最近更新 更多