How to pluck an associated model’s attribute in Rails

Say there are 2 models, Teacher and Subject.Association from Teacher to Subject can be has_one or has_manyThe model Subject has an attribute subject_name. So how can you pluck all the subject_name that belongs to at least one teacher?

Ans:

1. For has_one:

Teacher.joins(:subject).pluck(:"subjects.subject_name")

1. For has_many:

Teacher.joins(:subjects).pluck(:"subjects.subject_name")

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s