How to get activerecord associations via reflection

后端 未结 3 705
孤街浪徒
孤街浪徒 2020-12-23 00:04

For normal columns, you can get at them via the columns class method. However, associations may be named something quite different if the foreign_key

3条回答
  •  礼貌的吻别
    2020-12-23 00:32

    For future Googlers in Rails 4 the answer would now be:

    Post.reflections[:comments].foreign_key # => "message_id"
    

    Taken from here: https://stackoverflow.com/a/15364743/2167965

    EDIT:

    reflections, as of 4.2, now takes strings instead of symbols which is a fun bug to track down. If you want to keep using symbols you should switch to reflect_on_association(:assoc_name). Also note reflections are actually the public api which will keep reporting things like HABTM, even though it's all has many through under the hood. The reflections Rails is actually using are now in _reflections

提交回复
热议问题