1

The following tag in a nested form

<%= check_box_tag "friend_ids[]", ff.id, @contentrestrictions.friends.include?(ff.id) %>

is handling the following array of records

>> @contentrestrictions

[
#<Contentrestriction id: 29, usercontent_id: nil, friend_id: nil, created_at: "2019-04-28 10:55:32", updated_at: "2019-04-28 10:55:32">, 
#<Contentrestriction id: 30, usercontent_id: nil, friend_id: 2, created_at: "2019-04-28 10:55:32", updated_at: "2019-04-28 10:55:32">, 
#<Contentrestriction id: 31, usercontent_id: nil, friend_id: 4, created_at: "2019-04-28 10:55:32", updated_at: "2019-04-28 10:55:32">]

Even though

class Contentrestriction < ApplicationRecord
  belongs_to :friend, optional: true

@contentrestrictions. followed by any of friend_id, friend_ids both appended with or without [] all lead to NoMethodError: undefined method for Array.

how can this include function get a proper array to work with?

2
  • 1
    <%= check_box_tag "friend_ids[]", ff.id, @contentrestrictions.pluck(:friend_id).include?(ff.id) %>. Consider asign @contentrestrictions.pluck(:friend_id) to a variable if used more than one time in the template. Commented Apr 28, 2019 at 12:27
  • Goodness gracious! I use pluck all the time, but it did not dawn on me here! Commented Apr 28, 2019 at 12:44

1 Answer 1

1

the issue is in this line:

@contentrestrictions.friends.include?(ff.id)

you are comparing a friend object with a friend id, you could use pluck to get the friend ids, or you could just compare the objects:

@contentrestrictions.friends.include?(ff)

this will make a query for the .friends and you could remove this query by pre-loading the friends association, e.g. eager_load(:friends) or includes(:friends)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.