创建关联的模型实例以及主实例

时间:2014-07-25 21:33:11

标签: ruby-on-rails ruby rails-activerecord

与主要实例一起创建关联的模型实例

当我开车时,我也需要钥匙。我在Car#Create行动中做了两件事。这是正确与否?它会导致什么错误?应该怎么做?

虽然这有效,但它对我来说似乎不是Rubyist或RESTful。并不是说我是一个坚持不懈的人,但我希望这是正确的。谢谢......

  def create
    @car = Car.new(car_params)
    @key = Key.new(key_params)
    if @key.save and @car.save
      flash[:notice] = "Car has been created."
     else
      @key.destroy unless @key.nil?
      @car.destroy unless @car.nil?
      flash[:alert] = "Car has not be created."
    end
    redirect_to cars_path
  end

2 个答案:

答案 0 :(得分:1)

根据您的澄清,然后:

def create
  @car = Car.new(car_params)
  @car.build_key(key_params)
  if @car.save
    flash[:notice] = "Car has been created."
  else
    flash[:alert] = "Car has not be created."
  end
  redirect_to cars_path
end

在你的Car车型中你应该有这样的东西:

class Car < ActiveRecord::Base
  has_one :key, dependent: :destroy
  // all your other code
end

在你的方式中,未指定carkey之间的关联。

答案 1 :(得分:0)

我建议您在Car模型中验证是否存在密钥,并在after_create中为其创建密钥。

def create
  @car = Car.new(car_params, key_params)
  if @car.save
    flash[:notice] = "Car has been created."
   else
    @car.destroy unless @car.nil?
    flash[:alert] = "Car has not be created."
  end
  redirect_to cars_path
end

然后在你的车课里你应该有这样的东西:

class Car
  validates_presence_of :key
  after_create "create_key(key_params)"

  def create_key(key_params)
    self.key = Key.new(key_params)
  end
end

这一切都是从记忆中汲取的,所以如果有什么东西不合适,请告诉我,我会尝试修复它。