質問

model

class Clip < ActiveRecord::Base
  validates_length_of :description, maximum: 160
end

controller

  def update
    @clip = @film.clips.find_by_permalink(params[:id])

    respond_to do |format|
      if @clip.update(clip_params)
        format.html { redirect_to saas_admin_studio_film_path(@studio, @film), notice: 'Clip was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @clip.errors, status: :unprocessable_entity }
      end
    end
  end

view

<%= render 'saas_admin/shared/errors', resource: resource %>

<%= resource %> generates #<Clip:0x0000010c6c64e0> so resource is loaded. However, <%= resource.errors.any? %> returns false. If I change in controller @clip.update(clip_params) to @clip.update!(clip_params) I get:

Validation failed: Description is too long (maximum is 160 characters)

So the validation works, it's just that it's not taken by .errors to display it.

_errors

<% if resource.errors.any? %>
    <ul>
    <% resource.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
<% end %>

Any ideas why this is happening? Thank you.

役に立ちましたか?

解決

I don't think resource is the same Clip object as @clip.

Where in the code are you assigning @clip to be resource? I can't see where you have defined resource at all.

If you change it to be <%= render 'saas_admin/shared/errors', resource: @clip %> does the problem resolve?

他のヒント

As you have seen, though it probably seems backwards, the main difference between update and update! is how failed saves are handled.

When updating an ActiveRecord class the ! version will raise an exception if the record is invalid.

More info at http://api.rubyonrails.org/classes/ActiveRecord/Base.html

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top