0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

newメソッドとは

Posted at

Active Record

Active Recordオブジェクトは直接属性を明示するのではなく、むしろActive Recordオブジェクトを結合されるテーブル定義からActive Recordオブジェクトを推論する。属性、Active Recordオブジェクトを追加すること、削除すること、変更することはデータベースで直接実行する。変化は直ちにActive Recordオブジェクト上で反映される。特定のActive Recordクラスに特定のデータベーステーブルへ結びつける関数はほとんどの場合、自動的に起こる、しかし珍しい一つのケースに対して上書きすることができます

Active Record objects don’t specify their attributes directly, but rather infer them from the table definition with which they’re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.

irb(main):001:0> User
=> User (call 'User.connection' to establish a connection)
irb(main):002:0> User.superclass
=> ApplicationRecord(abstract)
irb(main):003:0> User.superclass.superclass
=> ActiveRecord::Base

ApplicationRecordとは?

class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class
end

primary_abstract_classとは

Active Recordのapplicationrecordクラスをセットする。もしアプリケーションがプライマリの抽象的なクラスとしてApplicationRecordとは違うクラスを使う場合これは便利です。このクラスはActive Recordを使ってデータベースコネクションを共有するだろう。プライマリのデータベースへ接続するクラスです。

  # Sets the application record class for Active Record
  #
  # This is useful if your application uses a different class than
  # ApplicationRecord for your primary abstract class. This class
  # will share a database connection with Active Record. It is the class
  # that connects to your primary database.

ApplicationRecordを別のクラス名に変えている場合は、primary_abstract_classを設定する必要があります。これにより、RailsはコネクションをどのクラスのActiveRecord::Baseと共有すべきかを認識できるようになります。

class PrimaryApplicationRecord < ActiveRecord::Base
  primary_abstract_class

  connects_to database: { writing: :primary, reading: :primary_replica }
end

この場合、primaryやprimary_replicaに接続するクラスは、標準のRailsアプリケーションがApplicationRecordで行っているのと同じように、プライマリの抽象クラスから継承できます。

class Person < PrimaryApplicationRecord
end

newメソッド

Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when you’re receiving the data from somewhere else, like an HTTP request. It works like this:

user = User.new(name: "David", occupation: "Code Artist")
user.name # => "David"

感想

newメソッドがどういう処理なのか知りたかったが現時点では無理だった。
どっちのnewを使っているのか?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?