如何在rails中保存属性

时间:2015-06-30 20:18:23

标签: ruby-on-rails ruby-on-rails-4

因为我刚开始使用rails ..我有一个非常简单的问题..这里我试图用

这样的属性保存一个新对象
      @receiver = User.find_by_email(params[:email])
      @sender = User.find_by_email(current_user.email)

      logger.info "@receiver.inspect"+@receiver.inspect
      logger.info "@sender.inspect"+@sender.inspect

      @newConnection = Connection.new
      @newConnection.user1 = @receiver.id
      @newConnection.user2 = @sender.id


      if @newConnection.save
       flash[:message] = "Saved Succesfully!"

但它的作用只是保存默认字段,而不是日志中的接收者和发件人ID

      INSERT INTO `connections` (`created_at`, `updated_at`) VALUES ('2015-06-30 20:14:30', '2015-06-30 20:14:30')

我的连接模型就像

       class Connection < ActiveRecord::Base
              attr_accessor :user1,:user2
              belongs_to :user1, :class_name => "User"
              belongs_to :user2, :class_name => "User"
       end

模型迁移

         class CreateConnections < ActiveRecord::Migration
         def change
create_table :connections do |t|
  t.integer :user1_id,  :references => [:users, :id]
  t.integer :user2_id,  :references => [:users, :id]
  t.date :connectedOn
  t.string :currentStatus

  t.timestamps
        end
     end
  end

请帮忙!

1 个答案:

答案 0 :(得分:1)

您应该分配用户对象,但不是它的ID ,如下所示:

@newConnection.user1 = @receiver
@newConnection.user2 = @sender

最重要的是从您的Connection模型中移除attr_accessor ,因此它将如下所示:

class Connection < ActiveRecord::Base
  belongs_to :user1, :class_name => "User"
  belongs_to :user2, :class_name => "User"
end

我还会将user1和user2命名为发件人和收件人或其他更有意义的名称。