处理控制器更新操作的collection_select

时间:2012-01-22 17:23:38

标签: ruby-on-rails ruby-on-rails-3 select controller

我有2个模特

第一个模型 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

第二个模型是 board.rb

class Board
 include Mongoid::Document

#Relationships
 belongs_to :category

  #fields
  field :name
  field :description

  #attr
  attr_accessible :name, :description

end

我有编辑电路板视图下一个表单:

<%= 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 %>

我在来自boards_controller.rb的更新操作下一步:

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

为什么我得到@ board.category_id为零?我想用我在select

中选择的值更新@ board.category_id

1 个答案:

答案 0 :(得分:0)

问题是@board.category_id = @category(您将对象设置为id字段)。它应该是

@board = Board.find(params[:id])
@category = Category.find(params[:category_id])
@board.category = @category

或者如果控制器和视图中没有使用@category,您可以编写

@board = Board.find(params[:id])
@board.category_id = params[:category_id]

第二个解决方案删除了​​类别

上的“SELECT”请求