Rails字段方法的调用

create_table "bank_cards", force: :cascade do |t|
    t.string "number"
    t.string "status"
    t.string "bank_name"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string "name"
    t.integer "age"
    t.string "phone"
    t.string "status"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

class User < ApplicationRecord
  has_many :bank_cards
end

class BankCard < ApplicationRecord
  belongs_to :user
end

上图为两个关联的一对多model,以及各自拥有的字段。

一、类可以把自己的字段当做方法调用。如:

user.name, user.phone, bank_card.user_id

二、一类调多类字段的时候,注意复数。如:

user.bank_cards.number

其中,s不能省,bank_cards方法在model关联中定义了。

三、多调一时,没有复数。如:

bank_card.user.age

你可能感兴趣的:(Rails字段方法的调用)