1
votes

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?

1

1 Answers

2
votes

Well, this is embarrassing. Just after posting this, I came up with an idea that ended up solving the problem:

class Message
  # ...

  def recipient_ids
    # ...
  end

  def recipient_ids=(arr)
    # ...
  end
end

I added the recipient_ids getter and setter, in addition to the association getter and setter that I had before.

Then I updated the form input field to refer to :recipient_ids instead of :recipients:

= simple_form_for(@message) do |f|
  = f.input :recipient_ids, as: :select, collection: Recipient.all