0

我是 Ruby on Rails 的新手,我遇到了一些问题

我正在尝试将类别 ID 影响到一个对象。

所以这是我的控制器动作:

  def create_card
    @card = Card.new(params[:card])

    if !params[:category].blank?
     @card.category_id = params[:category_id]
    end
    @category = Category.find(params[:id])
    @card.category_id = @category.id
    @card.save

    if @card.save
      flash[:notice] = "Card created"
      redirect_to :action => "card_information", :id => @card.id
    else
      render new_card_path
    end 
  end

这是我的观点代码:

= form_for @card, :url => create_card_path do |f|
  .row
    .span3
      = f.label "Card name"
      = f.text_field :title

  .row    
    .span3
      = f.label "Card Category"
      = select_tag :category_id, options_for_select(Category.all.collect{ |c| [c.title, c.id]})


  %br/
 .row
   .span3
     = f.submit "Submit", :class => "btn btn-primary"
4

1 回答 1

0

The category_id is already being passed into your controller as params[:card][:category_id], and is therefore already being assigned to @card when you do Card.new(params[:card]). So you can remove any code from your action where you're searching for the category, etc:

def create_card
  @card = Card.new(params[:card])

  if @card.save
    flash[:notice] = "Card created"
    redirect_to :action => "card_information", :id => @card.id
  else
    render new_card_path
  end 
end
于 2013-08-07T12:04:51.187 回答