Recently I have started to learn Rails.
Now, I'm implementing the Friendship relation in my own project. And here is the code some thing like that (some of them was collected from Internet)
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
When I create new Friendship from the console "rails c" it was OK when the 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
but when I set approved = false, it is down
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>
For the first time. I have thought it was the database(sqlite3) problem, but when I try this, from the sqlite3 terminal, it was fine
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
Can you tell me what happen and how to solve it.
You specify:
validates :approved, :presence => true
But in Rails:
false.present? # => false
Thus your validations are failing.
You can verify this by looking at the validation errors:
friendship = Friendship.create(:user_id=>6, :friend_id=>7, :approved=>0)
friendship.errors