ActiveRecord :: AssociationTypeMismatch错误通过另一个模型使用Rails 3将模型连接到自身

时间:2015-09-04 10:20:00

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord

我们有一个用户模型,在用户页面上,我们希望用户留下关于其他用户的引号,因此我创建了一个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 %>

1 个答案:

答案 0 :(得分:1)

  

ActiveRecord :: AssociationTypeMismatch(用户(#69931802297260)预期,   得到字符串(#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