Z
Z
zggb2015-03-04 13:12:57
Ruby on Rails
zggb, 2015-03-04 13:12:57

How to render errors?

Good day. Can't check image size before sending.
There is a real_estate model

has_many :pictures, dependent: :destroy
validate  :picture_size

def picture_size
    pictures.each do |img|
      if img.image_file_size > 5.megabytes
        errors.add(:pictures, "should be less than 5MB")
      end
    end
end

There is a controller
def update
    @user = current_user
    @real = RealEstate.find(params[:id])

    if @real.update(real_params)
      if params[:images]
        # The magic is here ;)
        params[:images].each do |image|
          @real.pictures.create(image: image)
        end
      end
    redirect_to root_path
  else
    render 'edit'
  end
end

and
def create
  @user = current_user
  @real = current_user.real_estates.build(real_params)

  if @real.save
    if params[:images]
      # The magic is here ;)
      params[:images].each do |image|
          @real.pictures.create(image: image)
      end
    end

    #flash[:success] = "Real Estate created!"
    redirect_to root_path
  else
    render 'real_estates/new'
  end
end

and here is the error handler
<% if object.errors.any? %>
  <div id="error_explanation">
  <div class="alert alert-danger">
    The form contains <%= pluralize(object.errors.count, "error") %>.
  </div>
  <ul>
  <% object.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
  </div>
<% end %>

In the update controller, errors are shown every other time, but in create they are not at all.
Perhaps the problem is in .build(real_params)
I unsuccessfully tried to replace it with .create (real_params)
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Yuri, 2015-03-04
@Jazzis

It seems to me that the model should be added before_create :check_picture_size. Thus, the check will be performed before the image is created. If you want to be executed before saving, then replace with before_save.

4
4itosik, 2015-03-04
@4itosik

Of course, I could be wrong, but you first check for validation (if @real.save) and then the images are saved. With this implementation, pictures should not be saved, but there will be no errors about this either.

D
Dmitry Eremin, 2017-12-07
@EreminD

$.getJSON('ajax/goods.json',).then(function() {
  console.log(data);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question