【问题标题】:Ruby on Rails - Nested Attributes and Automatic object creationRuby on Rails - 嵌套属性和自动对象创建
【发布时间】:2014-06-24 23:18:27
【问题描述】:

我问过之前的question,然后这个...

我有 3 个模型:合同、附录和预约

Contract.rb
  has_many :addendums
  accepts_nested_attributes_for :addendums

Addendum.rb
  belongs_to :contract
  has_many :appointments

Appointment.rb
  belongs_to :addendum

创建附录时,会自动创建一些约会。我做了这项工作,像这样在Addendum's Controller 上添加了一个函数

def createNewAppointments
  appointment = Appointment.new(params[:appointment]);
  appointment.dataprovavel = @addendum.data
  appointment.addendum_id = @addendum.id
  appointment.appointment_state = AppointmentState.where(descricao:'Pendente').first
  appointment.save 
  ...
end

这里调用了这个函数

Addendum Controller
def create
  respond_to do |format|
  if @addendum.save
    format.html { redirect_to @addendum, notice: 'Addendum was successfully created.' }
    format.json { render action: 'show', status: :created, location: @addendum }
    createNewAppointments
  else
  ...
end

现在,因为我开始在 Contract 和 Addendum 之间使用nested_attributes,所以新的 Addendum 是使用 build 方法创建的,所以函数 createNewAppointments 没有被调用...我该怎么做?

我尝试在模型Addendum 上使用after_create createNewAppointments,但它不起作用。它给出了一个错误Uninitialized constant Contract::Addendum

【问题讨论】:

  • 这个Addendum Controller 表示class AddendumsController?

标签: ruby-on-rails-4 nested-attributes


【解决方案1】:

您必须将方法从控制器移至合同模型。模型无法访问控制器方法。

并将@addendum 替换为self。然后从控制器调用它:

@addendum.createNewAppointments(params[:appointment], 'pendente')

请注意,您需要将参数从控制器传递给模型以使其工作。

def createNewAppointments(appointment, descricao)
  appointment = Appointment.new(params[:appointment]);
  appointment.dataprovavel = self.data
  appointment.addendum_id = self.addendum.id
  appointment.appointment_state = AppointmentState.where(descricao: descricao).first
  appointment.save 
  ...
end

您的另一个选择是将方法移至正在执行工作的合同控制器。只要附录控制器似乎没有交互。

然后做一些类似的事情:

@addendum = contract.build....
create_new_appointments

提示:在命名方法上使用 rails 约定。用户小写下划线。不要进行 JAVA 命名。

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多