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?
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.