mysqlruby-on-railsrubyruby-on-rails-4collection-select

Filter by user.id using collection_select for drop down in form


My first SO posting. Finally found something that has stumped me and after 6+ hours, I've decided I need some help, before I lose my mind.

I'm trying to use collection_select for a drop down list in a field to create a new record in a second model. My goal is to populate a list of records created by individual users from the Accounts model, a shared database, in a form to create a record in a new model named Assets.

I've set the Accounts form to store the auto generated record id for the user who creates an entry, so I should be able to reference it somehow.

At this time the data populates in the drop down list and cab be saved, however it shows all of the entries made by all users instead of only those made by the user who is creating the new entry.

I'm sure there is some way to filter by current_user.id. I'm tried 100 thing i've found online and the closest I could get was a invalid argument error when it returned an integer representative of the user id I wanted.

Form tag:

<%= form.label :asset_location, id: :asset_asset_location %>
<%= collection_select(:asset, :asset_location_id, Account.all, :id, :account_name, {}, {:multiple => false}) %>

Controller tag:

  respond_to do |format|
  @asset.user_id = current_user.id if current_user
  if @asset.save
    format.html { redirect_to asset_path}
    format.json { render :show, status: :created, location: @asset }
  else
    format.html { render :new }
    format.json { render json: @asset.errors, status: :unprocessable_entity }
  end
end

I'm pretty new to Ruby/Rails and trying to figure out if there is a better way to filter the results populated in the drop down by the current_user.id

I've literally been at this all night and don't plan on sleeping until it's right, so any help would be greatly appreciated. hahaha


Solution

  • You should able to reference the accounts created by an user with current_user.accounts, so just replace Account.all with current_user.accounts

    <%= form.label :asset_location, id: :asset_asset_location %>
    <%= collection_select(:asset, :asset_location_id, current_user.accounts, :id, :account_name, {}, {:multiple => false}) %>