I have 2 models
The first model category.rb
class Category
include Mongoid::Document
# Relationships
has_many :boards, :dependent => :destroy , :autosave => true
accepts_nested_attributes_for :boards
#fields
field :name
#attr
attr_accessible :name, :boards_attributes
end
The second model its board.rb
class Board
include Mongoid::Document
#Relationships
belongs_to :category
#fields
field :name
field :description
#attr
attr_accessible :name, :description
end
I have in edit board view the next form:
<%= form_for [@board], :url => user_board_path do |f| %>
<%= f.text_field :name %>
<%= f.text_area :description, :cols =>72, :rows => 5, %>
<%= f.collection_select :category_id, Category.all, :id, :name%>
<% end %>
and I have in update action from boards_controller.rb the next:
def update
@board = Board.find(params[:id])
@category = Category.find(params[:category_id])
@board.category_id = @category
respond_to do |format|
if @board.update_attributes(params[:board])
format.html { redirect_to user_board_path(@board.user, @board), notice: 'Board was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: @board.errors, status: :unprocessable_entity }
end
end
end
Why I get the @board.category_id nil? I want update the @board.category_id with the value that I choose in select
The problem is
@board.category_id = @category(you set an Object to an id field). It should beor if
@categoryis not used in the controller nor in the view, you could writeThe second solution removes a “SELECT” request on the Categories