0

ユーザー モデルとロケーション モデルを作成しました (製品モデルも作成しましたが、一度に 1 つの問題がありました)。コンソールで遊んでいると、いくつかの結果に驚きました。

モデル

Class User < ActiveRecord::Base
# Before saving filters
  before_save { self.email = email.downcase }
  before_save :create_remember_token

# Validations
  validates :name, presence: true,
                   length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true,
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, length: { minimum: 6 }
  validates :password_confirmation, presence: true

# Associations
  has_many :owned_products, class_name: "Product",
                            foreign_key: "owner_id",
                            dependent: :destroy
  has_many :borrowed_products, class_name: "Product",
                               foreign_key: "borrower_id"
  belongs_to :location

  private

    def create_remember_token
      self.remember_token = SecureRandom.urlsafe_base64
    end
end


Class Product < ActiveRecord::Base
  validates :name, presence: true,
                   length: { maximum: 50 }
  validates :owner, presence: true

  belongs_to :owner, class_name: "User", foreign_key: "owner_id"
  belongs_to :borrower, class_name: "User", foreign_key: "borrower_id"
  belongs_to :location
end

Class Location < ActiveRecord::Base
  has_many :users
  has_many :products
end

移行

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.string :password_digest
      t.string :remember_token
      t.integer :location_id

      t.timestamps
    end
    add_index :users, :email, unique: true
    add_index :users, :remember_token
    add_index :users, :location_id
  end
end

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.integer :location_id

      t.timestamps
    end
    add_index :products, :location_id
  end
end

class CreateLocations < ActiveRecord::Migration
  def change
    create_table :locations do |t|
      t.string :address

      t.timestamps
    end
  end
end

ロケーション属性はアクセシブルです

class UsersController < ApplicationController
    .
    .
    .
  private

    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation, :location, :location_attributes)
    end
end

次に、コンソールに移動して次のように入力します。

User.create(name: "Wahou", email: "wahou@bim.com", password: "motdepasse", password_confirmation: "motdepasse")

私に与えるもの:

(0.2ms)  begin transaction
User Exists (0.4ms)  SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('wahou@bim.com') LIMIT 1
Binary data inserted for `string` type on column `password_digest`  SQL (1.1ms)  INSERT INTO "users" ("created_at", "email", "name", "password_digest", "remember_token", "updated_at") VALUES (?, ?, ?, ?, ?, ?)  [["created_at", Fri, 24 May 2013 12:27:38 UTC +00:00], ["email", "wahou@bim.com"], ["name", "Wahou"], ["password_digest", "$2a$10$OhJ7SLA.vxO4N8IkZAXXQOibYQoX6G6E9/mGgmDpm8Hj48p8riDE."], ["remember_token", "-O72ULpG2tjrZSSi0BFB5A"], ["updated_at", Fri, 24 May 2013 12:27:38 UTC +00:00]]
(148.6ms)  commit transaction
=> #<User id: 1, name: "Wahou", email: "wahou@bim.com", password_digest: "$2a$10$OhJ7SLA.vxO4N8IkZAXXQOibYQoX6G6E9/mGgmDpm8Hj...", remember_token: "-O72ULpG2tjrZSSi0BFB5A", admin: false, location_id: nil, created_at: "2013-05-24 12:27:38", updated_at: "2013-05-24 12:27:38"> 

次に、次のように入力します。

Location.create(address: "1, rue des prises de tête - Paris")

これは私に与えます:

(0.2ms)  begin transaction
SQL (6.0ms)  INSERT INTO "locations" ("address", "created_at", "updated_at") VALUES (?, ?, ?)  [["address", "1, rue des prises de tête - Paris"], ["created_at", Fri, 24 May 2013 12:27:22 UTC +00:00], ["updated_at", Fri, 24 May 2013 12:27:22 UTC +00:00]]
(121.6ms)  commit transaction
=> #<Location id: 1, address: "1, rue des prises de tête - Paris", street: nil, city: nil, postal_code: nil, country: nil, longitude: nil, latitude: nil, created_at: "2013-05-24 12:27:22", updated_at: "2013-05-24 12:27:22"> 

だから、完全に自信を持って、私はそれをします:

User.first.location = Location.first

これは私に与えます:

User Load (0.5ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
Location Load (0.4ms)  SELECT "locations".* FROM "locations" ORDER BY "locations"."id" ASC LIMIT 1
=> #<Location id: 1, address: "1, rue des prises de tête - Paris", street: nil, city: nil, postal_code: nil, country: nil, longitude: nil, latitude: nil, created_at: "2013-05-24 12:27:22", updated_at: "2013-05-24 12:27:22"> 

そして、私がタイプするUser.first.locationと、それは私に与えますnil!

だから私はどこかに何かを忘れたと思います。アイデアはありますか?

(ユーザーを製品ごとに置き換えると、まったく同じことが行われます...)


編集

だけ入力しようとしましたがUser.first.location_id = 1User.first.location常にnilです。

ユーザーの場所を定義するために私が見つけた唯一の方法は、そのように場所で彼を作成することです: Location.first.users.create(name: "Wahou", email: "wahou@bim.com", password: "motdepasse", password_confirmation: "motdepasse"). そして、それは機能します...しかし、ユーザーの場所を更新したい場合はどうすればよいですか?


編集2

入力すると

u = User.first

最初のユーザーが取得されているのがわかります:

User Load (0.4ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: 2, name: "Numero1 Person", email: "numero1@person.com", password_digest: "$2a$10$sNwoTjOL4eqW.clxbM5FcuiE0AmPgzr8Kz0ewXgddAvP...", remember_token: "OQ2ZnLhPutwePTqn49r5PQ", admin: false, location_id: 2, created_at: "2013-05-29 07:59:13", updated_at: "2013-05-29 09:22:00"> 

次に、 Location.first を最初のユーザーの場所に影響を与えます。

u.location = Location.first

最初の場所が取得されていることがわかります:

Location Load (0.4ms)  SELECT "locations".* FROM "locations" ORDER BY "locations"."id" ASC LIMIT 1
=> #<Location id: 1, address: "1, rue longue - 99999 LOIN - France", street: "1, rue longue", city: "LOIN", postal_code: 99999, country: "France", longitude: nil, latitude: nil, created_at: "2013-05-29 07:59:38", updated_at: "2013-05-29 07:59:38"> 

でも保存したい時は…

u.save

...うまくいきません!

(0.1ms)  begin transaction
User Exists (0.4ms)  SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('numero1@person.com') AND "users"."id" != 2) LIMIT 1
(0.2ms)  rollback transaction
=> false 

編集3

次のコードを入力しようとすると...

User.first.update_attributes(location: Location.first)

それは私にそれを送り返します:

User Load (0.4ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
Location Load (0.3ms)  SELECT "locations".* FROM "locations" ORDER BY "locations"."id" ASC LIMIT 1
 (0.1ms)  begin transaction
User Exists (0.4ms)  SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('numero1@person.com') AND "users"."id" != 2) LIMIT 1
 (0.2ms)  rollback transaction
=> false 

解決した

恥ずかしい!update_attributes にパスワードと password_confirmation を追加するのを忘れています。私がそれをすれば、それはうまくいきます!

正しいコードは次のとおりです。

User.first.update_attributes(password: "password", password_confirmation: "password", location: Location.first)
4

2 に答える 2