2

I'm attempting to build a form which allows a user to select multiple Labels when creating a new Item, without allowing the user to create new Labels.

Here's how my models are set up:

Item
has_many :item_labels
has_many :labels, :through => :item_labels

ItemLabel
belongs_to :item
belongs_to :label

Label
has_many :item_labels
has_many :items, :through => :item_labels

Any ideas how I could create this sort of relationship within a form without allowing the user to create new labels? (Label creation is only done by the admin.)

Specifically, how should I set up the form in the view, and are there any changes I should make to my models? (accepts_nested_parameters or other directives)

2 Answers 2

1

I don't think you'll need accepts_nested_attributes for this. I haven't tried all this out, so YMMV :)

Here's how you might set up a new item in your controller. I'm setting a @labels instance variable, too, since I'll use that in a collection_select in the view:

# items_controller.rb
class ItemsController < ApplicationController
  def index
    @items = Item.all
  end

  def new
    @item = Item.new
    @labels = Label.all
  end

  def create
    @item = Item.new(params[:item])

    if @item.save
      flash[:info] = 'Item successfully created.'
      redirect_to items_path
    else
      @labels = Label.all
      render :new
    end
  end
end

Assuming your Label model has a name attribute, your form could look like this:

# new.html.erb
<%= form_form @item do |f| %>
  <!-- Other item fields go here -->

  <%= f.label :label_ids %>
  <%= f.collection_select :label_ids, @labels, :id, :name, {}, multiple: true %>

  <%= f.submit %>
<% end %>

You can read some more about collection_select to learn a bit more about that.

Sign up to request clarification or add additional context in comments.

1 Comment

@Rob glad to hear it!
1

Well, what part are you stuck on?

For the UI side, you might consider the chosen-rails gem:

https://github.com/tsechingho/chosen-rails

It lets users just start typing the name of an item and it helps them auto-complete it, similar to what happens when you select recipients for a message in Facebook. I think you should be able to use it to let the user select multiple labels.

1 Comment

I know if I'm creating new objects I would do something like f.fields_for :labels do... Then edit the model to accept_nested_attributes. Is it done similarly with existing objects? I can't seem to find this anywhere on google

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.