vendredi 4 septembre 2015

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

We have a User model and on the user pages we'd like users to leave quotes about other users, so I made a user_quote model, and a modal form in which the users can put the quote.

I'm getting the following error when I attempt to create

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'

I'm pretty sure I've made a mistake in the associations, but after a few hours searching for a solution and trying different things. I thought I would ask on here.

Here's the relevant code:

Models

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 

Migration

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

Controller

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 on page

<%= 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 %>

Aucun commentaire:

Enregistrer un commentaire