最近、私は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
コンソール「railsc」から新しいフレンドシップを作成すると、承認された=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
しかし、承認済み= 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
何が起こり、どのように解決するか教えてください。