A
A
artem_music2016-12-09 14:28:13
Ruby on Rails
artem_music, 2016-12-09 14:28:13

How to get a join table field?

There are two models - Member (participant) and Community (community).
Members can be in multiple communities. The migration and model data looks like this:

#models/member.rb
class Member < ActiveRecord::Base
  has_and_belongs_to_many :communities
end

#models/community.rb
class Community < ActiveRecord::Base
  has_and_belongs_to_many :members
end

#миграция
create_table :communities_members, id: false do |t|
      t.belongs_to :member, index: true
      t.belongs_to :community, index: true
      
      t.timestamps null: false #это важная строчка
end

The links work, I can easily get the members of the group by querying @community.members, etc., but I also need to see the time the link was created (when the person joined the group). To do this, I added the line t.timestamps - in theory, it should automatically add the created_at and updated_at columns.
But I don't understand how to get this value using the active record interface. Can you tell me?
Thanks in advance for your replies.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Viktor Vsk, 2016-12-09
@artem_music

Just for such purposes, it is recommended to use has_many through instead of has_and_belongs_to_many:

A
Anton, 2016-12-09
@hummingbird

@community.communities_members
Or with the help .joins
Or register scopein one of the existing models.
In fact, there are many ways to implement your idea.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question