Reputation: 37
Followed this guide by railscasts to setup autocompletion on collection_select. https://www.youtube.com/watch?v=M7yhPlIehFA In my example I'm trying to create a chatroom with a game related.
MODEL
belongs_to :game
validates :game, presence: true
def game_name
game.try(:name)
end
def game_name=(name)
self.game = Game.where(name: name).first_or_create if name.present?
end
CONTROLLER
def create
@room = current_user.chatrooms.build(room_params)
if @room.save
redirect_to @room
else
render 'new'
end
end
def room_params
params.require(:chatroom).permit(:title, :description, :game_id)
end
HTML
<%= simple_form_for @room do |f| %>
<p class="ftitle">Chatroom title</p>
<%= f.input :title, label: false %>
<p class="ftitle">Chatroom description</p>
<%= f.input :description, label: false %>
<p class="ftitle">Select related game</p>
<%= f.text_field :game_name, data: { autocomplete_source: Game.order(:name).map(&:name) } %>
<%= f.button :submit %>
<% end %>
It works fine until I try to create a chatroom with a game attached. It won't attach the game_id as a game. Not sure why. Thanks.
Upvotes: 0
Views: 37
Reputation: 14268
Trying to link the game based on name seems quite brittle and open to future abuse.
However if that's really what you want to do, add :game_name
to the .permit
method in room_params.
It would be more robust to pass through an ID here, rather than plain text.
Upvotes: 1