Search code examples
ruby-on-railsruby-on-rails-5simple-form

Rails 5.2 Simple Form Lambda Function


How do you use lambda functions for the data attributes in the input_html?

Let's say I have an Author model and a Book model. An Author can have many books, a Book can only have one author.

In the form for the Author model. I have the following -

<%= f.association :books, as: :check_boxes %>

I wanted to have a data attribute of the book's ISBN, like so -

<%= f.association :books, as: :check_boxes, input_html: {data: {isbn: lambda {|book| book.isbn} }} %>

But this does not work. Any ideas on how I might achieve this?


Solution

  • I don't think that's in simple_form's input_html API ... but you can always build the collection and pass it to the input like this (not tested):

    <% collection = f.object.books.map { |book| [book.id, book.name, data: { isbn: book.isbn }] } %>
    <%= f.association :foo, as: :check_boxes, collection: collection %>
    

    You would probably need to initialize the collection in Author#new, or you may want to avoid using f.association and just use f.input once you're passing the collection ... but I hope this steers you toward the right direction. Let me know what's the winning option!