Jonathan
Jonathan

Reputation: 683

Dropdown Menu Rails

I currently have categories seeded to my database within a 'category' model, what I'm trying to do is have a dropdown on the new post page which allows me to select what category it belongs to.

The problem is I'm currently getting below:

enter image description here

This is the field I'm currently using within the form.

  <div class="field">
    <%= f.select :category, Category.all, :prompt => "Select One" %>
  </div>

Any help would be fantastic.

Thanks

UPDATE

Offers Controller Create

  def create
    @offer = Offer.new(offer_params)

    respond_to do |format|
      if @offer.save
        format.html { redirect_to @offer, notice: 'Offer was successfully created.' }
        format.json { render :show, status: :created, location: @offer }
      else
        format.html { render :new }
        format.json { render json: @offer.errors, status: :unprocessable_entity }
      end
    end
  end

Upvotes: 0

Views: 39

Answers (2)

dom
dom

Reputation: 509

Instead of doing Category.all - which gives you back an ActiveRecord Object you have to specify the attribute on the Object you want.

There is a built in form helper for that:

<%= f.collection_select(:category_id, Category.all, :id, :name) %>

Rails guides for form helpers might help: http://guides.rubyonrails.org/form_helpers.html

Upvotes: -1

dimakura
dimakura

Reputation: 7655

Try using this:

<%= f.select :category_id, Category.all.collect{|c| [c.name, c.id]}, :prompt => "Select One" %>

More info can be found here.

Don't forget to add :category_id to permitted parameters list for Post in your controller.

Upvotes: 2

Related Questions