Rails控制器将错误的值保存到DB

时间:2011-11-02 14:14:15

标签: ruby-on-rails ruby controller

在我的relations_controller中,我有以下内容:

class RelationshipsController < ApplicationController

  def new
    @user = User.find_by_id(params[:user_id])
    @relationship = Relationship.new

  end

  def create
    @user = User.find_by_id(params[:user_id])
    @relationship = Relationship.new(params[:relationship])
    @relationship.rel_id = params[:user_id]
    @relationship.user_id = current_user

    @event = Event.new
    @event.user_id = @user
    @event.user_id = current_user
    @event.m_type = 'relationship'
    @event.text = 'wants to be friends with you.'
    @event.save

    @message = Message.new
    @message.sender_id = current_user
    @message.reciever_id = @user
    @message.subject = "New Friend Request"
    @message.body = "Hello, \n I'd like to connect with you as..."
    @message.save


    if @relationship.save
        redirect_to root_url, :notice => "Signed Up!"
    else
        render "new"
    end
 end
end

事件和关系会以正确的值保存,但无论我做什么,@ message都始终以1为sender_id和receiver_id保存。作为测试,我在那里硬编码了值并且那些工作,那么@evernts和@message之间发生了什么改变值?

2 个答案:

答案 0 :(得分:3)

@message.sender_id = current_user.id

@message.sender = current_user

但不是

@message.sender_id = current_user

您正在将对象分配给整数

答案 1 :(得分:2)

您尝试将_id字段设置为实际的ActiveRecord对象而不是整数。相反,试试这个:

@message.sender = current_user
@message.receiver = @user

或者:

@message.sender_id = current_user.id
@message.receiver_id = @user.id