1

最近开始学习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

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

4

1 回答 1

0

您指定:

validates :approved, :presence => true

但在 Rails 中:

false.present? # => false

因此,您的验证失败。

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

friendship = Friendship.create(:user_id=>6, :friend_id=>7, :approved=>0)
friendship.errors
于 2012-10-13T15:13:34.003 回答