A
A
Anton Misyagin2015-09-14 19:14:23
Ruby on Rails
Anton Misyagin, 2015-09-14 19:14:23

How to setup has_one association for model editing?

There is a model1 model, it has_one: model2
There is a route for making changes to model1:

class Model1Controller
  def update
    @model1 = Model1.where(params[:id]).first
    @model1.with_lock do
      @model1.update_attributes({:model1attr, :model2_attributes=>{:model2attr}})
      if @model1.errors.empty?
        flash[:success] = "все хорошо"
      else
        flash[:error] = "все плохо"
      end
      redirect_to кудабытонибыло
    end
  end
end

The problem is that when editing a record in the related table model2, the query is constructed in such a way that the related record is deleted and then a new one is inserted (in the logs there are 2 queries delete model2, insert model2). then insert does not happen and the record is lost.
Question 1. Is it possible to configure the behavior of the rail in such a way that it calls an update request on the associated model
Question 2. If this is not possible, then how to cancel the deletion of the associated record, the transaction in the form that is presented does not save

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jarosluv, 2015-09-15
@jarosluv

Updating a connected model is standard Rails behavior. If your application behaves differently, you need to understand, look at the accompanying code (models, views, at least).
I also suggest that you try to reproduce your error on a minimally working application (2 models and a controller), and post the code on Github.
I’ll also note that connected models are already updated through transactions, so the method with_lockis superfluous.

T
The Whiz, 2015-09-17
@modernstyle

The question is too complex. Are you wondering if it's possible to update updated_at on related models when editing the parent? You can, through a hook in the model, for example:

after_save do
  model.update_attribute(:updated_at, Time.now)
end

Or even better usemodel.touch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question