Radio buttons in Ruby on Rails don't combine well with join tables and the need to have several in a page. This presentation and associated code show a demo with two ways to solve this, one in pure RoR, the other adds in JS and SCSS to make the end result prettier.
4. Scenario
A typical context that needs multiple radio button options on a single page
● Multiple users adding review feedback
● Multiple things to be reviewed
Example sites with these capabilities
● TripAdvisor
○ Hotels
○ Restaurants
● GoodReads
○ Books
14. Form param syntax - best practice?
Is the param syntax correct / best practice?
● I have no idea
User[books_user][4][score] or User[books_user][user_id][4][score] or … ?
● Possible to build any syntax you want
● As built:
○ Succinct
○ Straightforward to parse in the controller
15. Controller
def update
book_params[:books_user].each do |param|
next unless param.last[:score]&.present?
BooksUser.create(user_id: @user.id, score: param.last[:score].to_i,
book_id: param.first.to_i)
end
redirect_to user_path(@user)
end
def book_params
params.require(:user).permit(books_user: :score)
end
16. View / controller - best practice?
Is it correct / best practice to use edit / put / update?
● I have no idea
The controller code creates join entries
● Natural fit would be new / post / create, BUT
● Create optimised for single create, not multiple
● Both the books and the user already exist
○ We’re only gluing them together with a join table entry
19. View
<% @books.each do |book| %>
<%= f.fields_for "books_user][#{book.id}" do |ff| %>
<td class=”book-score” book=<%= book.id %>>
<!-- CSS uses right-to-left, so star index is reversed, ie from 4 to 0 -->
<% star_index = 4 %>
<% 5.times do %>
<span class=”icon” onClick=”clickStar()” score=<%= star_index
%>></span>
<% star_index -= 1 %>>
<% end %>
...
Stash the book id for JS to find
JS entry point