I'm having trouble with the create action in my plannings_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

In the #new action, the find_plannable method returns the value I want, but in the #create action it returns nil and I have no idea why this is happening.

My models are just like Ryan Bates' in the rails cast polymorphic episode:

#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

Can anyone help me?! thanks in advance!

edit: parameters:

{"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"}
有帮助吗?

解决方案

In the POST parameters, there isn't such a field matching /(.+)_id$/, so, your attempt to find the class will fail inside find_plannable

The simple fix is, in #new, add a hidden field of the plannable_id inside the form. You've already got @plannable there, so that's easy.

Then you'll have plannable_id and its value to feed find_plannable.

其他提示

Have you checked your params it seems that you are having different value for params in case of create and new. Can you please post params hash for both create and new, it may help others is solving your problem

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top