【问题标题】:Update in action create更新在行动创建
【发布时间】:2015-09-08 01:17:11
【问题描述】:

我有三个模型,auto、perfil 和 user。每个用户都有自己的个人资料。我需要当您发布新汽车时,如果数据不同或及时更改,您可以更新您的个人资料用户。但不像用来更新action create中的action。我使用嵌套属性。

 def create
         current_user.perfil||= current_user.build_perfil
         @perfil = current_user.perfil
         @perfil.update_attributes(auto_params)

         @auto = @current_user.autos.new(auto_params)
          respond_to do |format|
       if @auto.save 
        format.html { redirect_to @auto, notice: 'Auto was successfully created.' }
        format.json { render :show, status: :created, location: @auto }
       else
         format.html { render :new }
         format.json { render json: @auto.errors, status: :unprocessable_entity }
      end
     end

【问题讨论】:

  • 您好,您遇到的具体问题是什么?你已经尝试过什么?

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


【解决方案1】:

我认为您要问的是,每当创建“自动”对象时,如果数据有一些变化并且您不想在“创建”方法中更新“用户”配置文件,则应该更新“自动控制器”

你可以做的是,在你的“自动”模型中

include ActiveModel::Dirty

并定义一个

after_commit :update_user_profile, on: :create

在您的“自动”模型和回调函数中

def update_user_profile

prev_changes = self.previous_changes

end

现在使用“prev_changes”,您可以检查适当的更改并相应地更新“用户”模型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    相关资源
    最近更新 更多