hyperrjas
hyperrjas

Reputation: 10744

undefined method `first' Mongoid

I have 2 models:

board.rb

class Board
 has_and_belongs_to_many :posts, :autosave => true
end

post.rb

class Post
 has_and_belongs_to_many :boards
end

In my posts_controller.rb

def create
 @post = current_user.posts.new(params[:post])
 @post.save
end

In my view posts I have a form with collection_select field:

<%= form_for(@post) do |f| %>
 <%= f.submit %>
<%= f.collection_select :board_ids, Board.where(:user_id => current_user.id), :id, :name%>
<% end %>

I get with type relation has_and_belongs_to_many the next error:

undefined method `first' for BSON::ObjectId('4f2e61ce1d41c8412a000215'):BSON::ObjectId

:board_ids is an array type board_ids: [] in object Post.

How save the object from field collection_select in this array?

Upvotes: 0

Views: 1388

Answers (2)

niwo
niwo

Reputation: 11

If you want to use a select you need to specify the html option "multiple" in order to submit an array of options.

<select multiple="muliple"> ...

My working Rails form (using simple_form) looks like this:

<%= simple_form_for @exercise, :html => { :multipart => true } do |f| %>
   <%= f.input_field :category_ids, :multiple => "multiple", :as => :grouped_select, :collection => CategoryGroup.all, :group_method => :categories %>
<% end %>

Upvotes: 1

Steve
Steve

Reputation: 15736

The problem here seems to be that you are using a drop down list to map to a multi-valued field (board_ids). So your application is trying to set the board_ids field to a single value (a BSON::ObjectId) when mongoid is expecting an array.

If a Post can be associated with many Boards (and assuming you don't have a very large number of boards for a given user) then perhaps a better way to get this working is to use a set of checkboxes rather than a single drop down list.

<% Board.where(:user_id => current_user.id).each do |board| %>
  <%= check_box_tag 'post[board_ids][]', board.id, @post.board_ids.include?(board.id) %>
  <%= board.name %>
<% end %>

Upvotes: 0

Related Questions