Home > database >  What is map(&:id) in Rails?
What is map(&:id) in Rails?

Time:06-02

My question is not an error, it is for understanding. As I'm new to Rails, I can't read all the code yet.

  1. what does (&:id) do after .map

    @user_cnae_classifications = user.cnae_classifications.map(&:id)
    

    what is the difference of .map with it and without it?

  2. in this method call:

    UserCnaeClassification.create(
      user: @user,
      cnae_classification_id: id
    )
    

    How do I read that part of the code...

    user: @user,
    cnae_classification_id: id
    

    are they keys and values?

CodePudding user response:

1 ) You should read some tutorials on map to get acquainted. Ruby Map Method Diagram

2 ) The #create method can accept a key-value hash of known attributes (known to the class in question, in this case that is UserCnaeClassification) to assign upon creation. So you're basically right, they are key-value pairs but they are specific to this class/object. Those same keys might not work on another class/object. Additional reading: enter image description here

enter image description here

Usage: enter image description here Also pluck doesn't work with regular Arrays.

  • Related