I'm making a hotel app that includes Room
and RoomAttribute
models. The two models have a many_to_many
relationship between each other through a join table. The attributes for each model are as follows:
Room
–room_number
,room_type
(e.g. "deluxe" or "suite"), andprice
.RoomAttributes
–name
(e.g. "Wireless Internet", "Cable TV", "Bath Tub").
The user will first create a set of room attributes, so that these can be selected as checkboxes every time a new room is created. For example, some rooms may have wireless internet and some don't. The code for app/views/rooms/new.html.erb
is (my apologies for using raw html).
<form action="<%= rooms_path %>" method="post">
<input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>">
<label for="room_number">Room Number:</label>
<input type="text" name="room[room_number]" id="room_number"> <br>
<label for="room_type">Type:</label>
<input type="text" name="room[room_type]" id="room_type"> <br>
<label for="price">Price:</label>
<input type="text" name="room[price]" id="price"> <br>
<label for="room_attributes">Attributes:</label>
<ul>
<% @room_attributes.each do |room_attribute| %>
<li>
<input type="checkbox" name="room[room_attributes_ids][]" value="<%= room_attribute.id %>">
<%= room_attribute.name %>
</li>
<% end %>
</ul>
<input type="submit" value="Submit">
</form>
I'm using Rails 4 and I'd like to ask for advice on the following:
- Set up the form using form helpers or formtastic so that it already outputs all the pre-defined room attributes and users can simply select which attributes to include in the room via checkboxes.
- Write
RoomController#create
method for this so that it sets the nestedRoomAttribute
models as room attributes. Do I needaccepts_nested_attributes_for :room_attributes
in myapp/models/room.rb
? How to incorporate strong parameters in this scenario. I've read that I should use
params.require(:room).permit(:room_number, :room_type, :price, room_attributes_attributes: [:id])
but this is not working for me.
Thank you! :)