创建模型实例的问题 - Ruby on Rails中的TypeMismatch错误

时间:2013-05-02 18:04:13

标签: ruby-on-rails

我收到错误,我不明白为什么。我有一个表单传递给控件输入以创建一个模型实例。

以下是表格:

=form_for :message, :url => {:action => 'create', :controller => 'messages'} do |f|
    =f.text_area :body, :placeholder => 'Enter your message.', :size => '40x5'
    =f.hidden_field :subject, value: "RE:#{@message.subject}"
    =f.hidden_field :parent, value: @message.id
    =f.hidden_field :receiver, value: @message.sender
    =f.submit 'Reply'

这是控制器:

def create
    user = User.find_by_username(params[:message][:receiver])#remove receiver and give it a varibale -rg 4/29
    if user ||= User.find_by_id(params[:message][:receiver]).username#valid entry -rg 4/29
        params[:message].delete('receiver')
        params[:message][:status] = 'unread'#set status -rg 4/29
        params[:message][:sender] = @current_user#set sender -rg 4/29
        # raise params.inspect
13 =>   @message = Message.create!(params[:message])#create message! -rg 4/29
        if parent = params[:message][:parent]#checks if this is a reply to another message -rg 4/29
            Message.find_by_id(parent).update_attributes(:child => @message)#updates parent message to have this message as child -rg 4/29
        end
        @message.received<<user#adds receiver to database
        flash[:notice] = "Message was successfully sent."
        redirect_to messages_path
    else
        flash[:warning] = "There is no user with that username."
        redirect_to messages_path
    end
end

我的消息模型:

class Message < ActiveRecord::Base
   attr_accessible :body, :subject, :status, :sender, :receiver,:parent, :child
   belongs_to :sent, :class_name => 'User'
   has_and_belongs_to_many :received, :class_name => 'User'
   belongs_to :parent, :class_name => 'Message'
   has_one :child, :class_name => 'Message'
end

我得到的错误,包括追踪:

 ActiveRecord::AssociationTypeMismatch in MessagesController#create

 Message(#41016000) expected, got String(#17696120)

 Rails.root: /home/renee/classes/SE/Brainstormy
 Application Trace | Framework Trace | Full Trace

 app/controllers/messages_controller.rb:13:in `create'

以下是传递的参数:

{"utf8"=>"✓",
 "authenticity_token"=>"yLYTXNTjluDk15dm554vpjom7hlQCC2d+hGmkuLJcEE=",
 "message"=>{"body"=>"j",
 "subject"=>"RE:j",
 "parent"=>"1",
 "status"=>"unread",
 "sender"=>2},
 "commit"=>"Reply"}

这很有意思,因为我有第二种形式,它使用完全相同的控制器。似乎我所拥有的额外字段:parent是罪魁祸首。但我想不想传递消息。我想要的是传递一个id的整数。但它正以字符串形式传递。任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

这是因为您将字符串(f.hidden_field :parent, value: @message.id)传入需要Message对象的父关联方法。您要做的是将父关联的foreign_key字段设置为消息ID。

如果foreign_key是parent_id,则隐藏字段应为:

f.hidden_field :parent_id, value: @message.id

您必须检查提取:parent是否与使:parent_id可访问相同,否则无法设置。