关联方法的可选参数汇总

关联方法的可选参数汇总

belongs_to

valid_options

ActiveRecord::Associations::Builder::BelongsTo.valid_options nil

valid_dependent_options

ActiveRecord::Associations::Builder::BelongsTo.valid_dependent_options

has_one

valid_options

ActiveRecord::Associations::Builder::HasOne.valid_options through: 'fakers'

valid_dependent_options

ActiveRecord::Associations::Builder::HasOne.valid_dependent_options

has_many

valid_options

ActiveRecord::Associations::Builder::HasMany.valid_options nil

valid_dependent_options

has_and_belongs_to_many

和 has_many 一样。

实现关联对象:

参数

belongs_to

has_one

has_many

habtm

:class_name

:foreign_key

:foreign_type

:primary_key

:as

:through

:source

:source_type

:join_table

:association_foreign_key

:table_name

:autosave

:dependent

:before_add

:after_add

:before_remove

:after_remove

:validate

:required

:counter_cache

:polymorphic

:touch

:inverse_of

:anonymous_class

:optional

:extend

:index_errors

详解:

class_name

foreign_key

primary_key

as

through

source

source_type

foreign_type

optional

extend

join_table

association_foreign_key

autosave

dependent

validate

inverse_of

counter_cache

touch

required

readonly

polymorphic

inverse_of

index_errors

anonymous_class

before_add、after_add、before_remove 和 after_remove

心得

关系比较复杂的时候,不好写。我建议先从简单、可确定的入手,然后进行下一步。

例如:自关联,或者通过关联表实现关联,通常:

  • 表里有 xxx_id 等外键的,通常就是 belongs_to

  • 然后对应其关联的就是 has_many

  • 再之后就是 through

最后更新于

这有帮助吗?