0

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

这是表格:

=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。但它作为字符串传递。谁能帮我解决这个问题?

4

1 回答 1

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否则将无法设置。

于 2013-05-02T20:15:57.863 回答