There is an `collection_select` form builder that will do the `collect` for 
you. So:

    <%= f.collection_select :user, policy_scope(User), :id, :name %>

If you are not using a form builder then 
`options_from_collection_for_select` is useful for the same purpose.

If those helpers cannot be used directly for some reason I create a custom 
helper.

For example if I wanted to include the user's security role as a data 
attribute for some sort of UJS behavior I might have:

    def user_options selected
      policy_scope(User).collect do |user|
        content_tag 'option', user.name,
          value: user.id,
          selected: user.id == selected,
          data: { role: user.role }
        end.join.html_safe
    end

Then in the view I might have:

    <%= form.select :user_id, user_options form.object.user_id %>

On Tuesday, October 2, 2018 at 7:20:48 AM UTC-4, John Sanderbeck wrote:
>
> Good Morning Everyone...
>
> I have a coding question just so I am clear on the proper way to do this...
>
> To start, I have an app that I use Pundit in to control access to data, so 
> I have a lot of calls that are like policy_scope(User)
>
> What is the proper way to populate a select on a form with this data?
>
> Initially I was just using policy_scope(User).collect
>
> However I don't think it is proper to use this in a view, is it?
>
> If not, what is the proper way to pull this data and provide it to the 
> form?
>
> Recently I have moved some of these to helpers and created a method like 
> "users_for_select"
>
> John
>

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/5e458afd-02e5-4508-bbd6-2f1612d46727%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to