How to create a form that allows for adding to a collection belonging to the model?

Viewed 10

So, 2 of my models User and Character are in has_and_belongs_to_many association with a sole purpose of a user having a list of favourite characters. (i initally just wanted for user to has_many :characters, but with that I wasn't even able to get .characters method to work)

Anyway, I also created a migration that created a characters_users join table. How can I go about creating a form that during creating/updating a user would let me select a character and add associate it?

my new/create in UsersController

  def new
    @user=User.new
    @user.characters.build
  end

  def create
    @user = User.new(user_params)

    if @user.save
      redirect_to @user
    else
      render :new, status: :unprocessable_entity
    end
  end

and my form

<h1>Users#new</h1>


<%= form_with model: @user do |form| %>
  <div>
    <%= form.label :username %><br>
    <%= form.text_field :username %>
    <% @user.errors.full_messages_for(:username).each do |message| %>
      <div><%= message %></div>
    <% end %>
  </div>

  <div>
    <%= form.label :password %><br>
    <%= form.password_field :password %><br>
    <% @user.errors.full_messages_for(:password).each do |message| %>
      <div><%= message %></div>
    <% end %>
  </div>

  <div>
    <%=form.fields_for :character do |c|  %>
    <%= c.collection_select :character_id, Character.order(:name), :id, :name %>
    <% end %>
  </div>

  <div>
    <%= form.submit %>
  </div>

<% end %>

and when submitting the form a user IS created, it has a name and a password, however the selected character is not added to its .characters and absolutely nothing happens to the join_table rails doesn't throw any error or anything

i only have an issue with creating a correct form (and I assume I might need to change something in users_controller as well), as in rails console just using something like

User.find(5).characters<<Character.find(13)

works just fine - the join table is updated and I have no issue then showing the characters on my user show view

1 Answers

So, I found the answer to my problem. Apparently the issue is using "character_id" in the collection_select, as the method should be character_ids instead - due to a user having many characters. this fixed it

Related