ActiveRecord::AssociationTypeMismatch 通过 Rails 3 的另一个模型将模型连接到自身时出错

ActiveRecord::AssociationTypeMismatch error connecting a model to itself through another model with Rails 3

我们有一个用户模型,在用户页面上我们希望用户留下关于其他用户的引述,所以我制作了一个 user_quote 模型,以及一个用户可以在其中引用的模态表单.

我尝试创建

时遇到以下错误
ActiveRecord::AssociationTypeMismatch (User(#69931802297260) expected, got String(#18631480)):
  app/controllers/user_quotes_controller.rb:5:in `new'
  app/controllers/user_quotes_controller.rb:5:in `create'

我很确定我在关联中犯了一个错误,但在几个小时后寻找解决方案并尝试了不同的东西。我想我会在这里问。

相关代码如下:

型号

class User < ActiveRecord::Base

    has_many :quotes_made, :class_name => 'UserQuote', :foreign_key=>'quoter_id' 
    has_many :quotes_received, :class_name => 'UserQuote', :foreign_key=>'quotee_id'

end 

class UserQuote < ActiveRecord::Base
      attr_accessible :quoter_id, :quotee_id, :quote
      belongs_to :quoter, :class_name => 'User', :foreign_key=>'quoter_id'
      belongs_to :quotee, :class_name => 'User', :foreign_key=>'quotee_id'

end 

迁移

class CreateUserQuotes < ActiveRecord::Migration
  def change
    create_table :user_quotes do |t|
      t.integer :quoter_id
      t.integer :quotee_id
      t.text :quote
      t.timestamps
    end
  end
end

控制器

class UserQuotesController < ApplicationController
    def create
        @uq = UserQuote.new(:params[:user_quote])
        if @uq.save
            render json: UserQuote.where(:quotee => @uq.quotee).to_json
        else
            render json: @uq.errors, status: :unprocessable_entity
        end
    end
end

页面上的表格

<%= form_for UserQuote.new, remote: true, html: {'data-type' => :json} do |f| %>
    <div class='modal-body'>

        <%=f.hidden_field :quoter_id, :value=>@user.id %>
        <div class='form-group'>
            <%=f.label :quotee, {class: 'control-label'} %>
            <%=f.collection_select :quotee, User.all, :id, :name, {}, {class: 'form-control'} %>
        </div>
        <div class='form-group'>
            <%=f.label :quote, {class: 'control-label'} %>
            <%=f.text_area :quote, {class: 'form-control tinymce'} %>
            <%=tinymce%>
        </div>

    </div>
    <div class='modal-footer'>
        <div class='row'>
         <%=f.submit "Add Quote", class: 'btn btn-default' %>
         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>
<% end %>

ActiveRecord::AssociationTypeMismatch (User(#69931802297260) expected, got String(#18631480))

这一行

<%=f.collection_select :quotee, User.all, :id, :name, {}, {class: 'form-control'} %>

应该是

<%=f.collection_select :quotee_id, User.all, :id, :name, {}, {class: 'form-control'} %>

同样在user_quotes_controller,更改

render json: UserQuote.where(:quotee => @uq.quotee).to_json

render json: UserQuote.where(:quotee_id => @uq.quotee_id).to_json