0

createplannings_controller.

def new
  @plannable = find_plannable
  @planning = @plannable.plannings.build
  3.times { @planning.periods.build }

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @planning }
  end
end


def create
  @plannable = find_plannable
  @planning = @plannable.plannings.build(params[:planning])
  respond_to do |format|
    if @planning.save
      format.html { redirect_to @plannable }
      format.json { render json: @planning, status: :created, location: @plannable }
    else
      format.html { render action: "new" }
      format.json { render json: @planning.errors, status: :unprocessable_entity }
    end
  end
end


def find_plannable
  params.each do |name, value|
    if name =~ /(.+)_id$/
      return $1.classify.constantize.find(value)
    end
  end
  nil
end

#new动作中,该find_plannable方法返回我想要的值,但在#create动作中它返回 nil,我不知道为什么会这样。

我的模型就像 Rails cast 多态集里的 Ryan Bates 一样:

#PLANNING MODEL
class Planning < ActiveRecord::Base
  attr_accessible :subsubsystem_id, :subsystem_id, :system_id, :plannable_type, :plannable_id, :periods_attributes, :_destroy
  has_many :periods, :dependent => :destroy
  belongs_to :plannable, polymorphic: true
  accepts_nested_attributes_for :periods, :reject_if => lambda { |a| a[:planned_quantity].blank? }, :allow_destroy => true
end

#SUBSUBSYSTEM MODEL
class Subsubsystem < ActiveRecord::Base
  attr_accessible :hh, :name, :percentage, :price, :subsystem_id, :total_quantity, :unity, :value, :weight
  belongs_to :subsystem
  has_many :plannings, :as => :plannable
end

谁能帮我?!提前致谢!

编辑:参数:

{"utf8"=>"✓",
 "authenticity_token"=>"vSr7C1+3+RhYArAmYz+zuAsLXsXriwouF771bn79+Is=",
 "planning"=>{"periods_attributes"=>{"0"=>{"planned_quantity"=>"11"},
 "1"=>{"planned_quantity"=>"6"},
 "2"=>{"planned_quantity"=>"8"}},
 "_destroy"=>"0"},
 "commit"=>"OK"}
4

2 回答 2

0

您是否检查过您的参数,在创建和新建的情况下,您似乎对参数有不同的价值。您能否为 create 和 new 发布 params hash,它可能会帮助其他人解决您的问题

于 2013-11-05T13:21:05.920 回答
0

在 POST 参数中,没有这样的字段匹配/(.+)_id$/,因此,您在内部查找类的尝试将失败find_plannable

简单的解决方法是,在#new 中,在表单内添加 plannable_id 的隐藏字段。你已经到了@plannable那里,所以这很容易。

然后你将拥有plannable_id它的价值来喂养find_plannable

于 2013-11-05T14:44:30.720 回答