我们有一个用户模型,在用户页面上我们希望用户留下关于其他用户的引述,所以我制作了一个 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
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_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
关于ruby-on-rails - ActiveRecord::AssociationTypeMismatch 错误通过 Rails 3 的另一个模型将模型连接到自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32395656/