【问题标题】:Something was wrong when insert Record with false value in rails 3.2在 Rails 3.2 中插入具有错误值的记录时出现问题
【发布时间】:2012-10-13 15:06:59
【问题描述】:

最近开始学习 Rails。

现在,我正在我自己的项目中实现友谊关系。这是类似的代码(其中一些是从互联网收集的)

class Friendship < ActiveRecord::Base 

  attr_accessible :friend_id, :message, :user_id, :approved

  validates_uniqueness_of :user_id, :scope => [:friend_id]

  validates :approved, :presence => true
  belongs_to :user
  belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"

end

///////////////////

class User < ActiveRecord::Base
   has_many :friendships
   has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
   has_many :direct_friends, :through => :friendships, :conditions => { 'friendships.approved' => true }, :source => :friend
end

////////////////////

class CreateFriendships < ActiveRecord::Migration
  def change
    create_table :friendships do |t|
    t.integer :user_id
    t.integer :friend_id
    t.text :message
    t.boolean :approved, :default => false

    t.timestamps
  end
end

当我从控制台“rails c”创建新友谊时,approved = true

Friendship.create(:user_id=>7, :friend_id=>11, :approved=>1, :message=>'Be my friend :D')
(0.1ms)  begin transaction
SQL (0.9ms)  INSERT INTO "friendships" ("approved", "created_at", "friend_id", "message", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?)  [["approved", true], ["created_at", Sat, 13 Oct 2012 14:15:36 UTC +00:00], ["friend_id", 11], ["message", "Be my friend :D"], ["updated_at", Sat, 13 Oct 2012 14:15:36 UTC +00:00], ["user_id", 7]]
(12.2ms)  commit transaction

但是当我设置approved = false时,它就关闭了

Friendship.create(:user_id=>6, :friend_id=>7, :approved=>0)
(0.1ms)  begin transaction
(0.1ms)  rollback transaction
=> #<Friendship id: nil, user_id: 6, friend_id: 7, message: nil, approved: false, created_at: nil, updated_at: nil>

第一次。我一直以为是数据库(sqlite3)的问题,但是当我从sqlite3终端尝试这个时,它很好

sqlite> insert into friendships (user_id, friend_id, created_at, updated_at) values(11, 6, '2012-10-13 14:15:36', '2012-10-13 14:15:36');
sqlite> select * from friendships;
        id = 1
   user_id = 11
 friend_id = 6
   message = 
  approved = f
created_at = 2012-10-13 14:15:36
updated_at = 2012-10-13 14:15:36

你能告诉我发生了什么以及如何解决它。

【问题讨论】:

  • 这可能与验证有关。只需删除验证。反正也没用。

标签: ruby-on-rails sqlite3-ruby


【解决方案1】:

您指定:

validates :approved, :presence => true

但在 Rails 中:

false.present? # => false

因此您的验证失败。

您可以通过查看验证错误来验证这一点:

friendship = Friendship.create(:user_id=>6, :friend_id=>7, :approved=>0)
friendship.errors

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 2016-10-18
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    相关资源
    最近更新 更多