I have a Message
data model in Rails with a "virtual" association. That is, a method that returns a collection of "associated objects", but it is not an actual association in the ActiveRecord sense.
class Message
def recipients
@recipients
end
def recipients=(arr)
@recipients = arr
end
end
The thing with simple_form is that, when I try to show a association
field, it fails because there's no :recipients
association:
= simple_form_for(@message) do |f|
= f.association :recipients, collection: Recipient.all
The solution seemed then simple, I went on to use a f.input
with the as: :select
option:
= simple_form_for(@message) do |f|
= f.input :recipients, as: :select, collection: Recipient.all
And this works fine, except for the fact that it does not automatically detect the values already in @message.recipients
so that the elements appear pre-selected when the form is rendered.
If Message#recipients
were an actual association, in the ActiveRecord sense, then f.association
in the form would do this as well. But for reasons that go beyond the scope of this question, I can't make it as an actual association.
The question then is, can I achieve f.input :recipients, as: :select
to pre-select the selected elements?