我收到以下错误... ActiveRecord :: AssociationTypeMismatch设备(#xxxx)预期,得到字符串(#xxxx)
我无法确定这个错误的来源或解决方法。任何人都可以解释我的代码出错的地方吗?
Models =
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
LinksController =
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
DevicesController =
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
CreateLinks Database =
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>
答案 0 :(得分:0)
在链接模型中,您与列from_device
和to_device
建立了关联。您希望通过任何外键关联Links表。如下所示:
has_many :links, foreign_key: "from_device"
has_many :links, foreign_key: "to_device"
看看是否有帮助。您的设备型号也是如此。