Ask A Question

Notifications

You’re not receiving notifications from this thread.

Newbie question trying to understand collection_check_boxes method

MH asked in Rails

Hi, I am new to Rails, and I am trying to create checkboxes in a view. I came across this method:
https://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_check_boxes

What I am trying to understand here is, where does this “:author_ids” method come from? Is this similar to author.ids method? I have been reading through the guide but struggling to find out where is the method coming from? Also I do not quite understand the purpose of parsing this “:name_with_initial” into the method.

Appreciate for any advice/explanation on this.

Reply

That would come from a has_may :authors association. ActiveRecord knows how to handle those associations through those methods.

It's documented here as collection_singular_ids https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Reply

As I understand it, author_ids is one of those Rails built-in magic merhods that gives you all the IDs of associated records. For example, if I have a School that has_many :teachers I can do School.find(1).teacher_ids to get all the IDs of all the teachers associated with that school. Super handy and saves writing some gnarly SQL.

The name_with_initial method is generating the text shown alongside the checkbox. It could just be a plain text column from Author, like first_name but this is showing you how you can spruce it up a bit and use a method to generate fotmatted text instead.

Reply

hello

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,400+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.