rails中的验证错误

时间:2016-05-21 23:26:49

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

我在使用rails时遇到一些问题,我们将不胜感激。我有一个动作

def submit_solution
    @event = Event.find(params[:id])
    @gallary = @event.gallaries.new
end 

从此进入视图

<%= form_for @gallary do |f| %>
    <%= render 'shared/error_messages', object: @gallary %>

    <div class="field">
       <%= f.label :image %><br>
       <%= f.file_field :image %>
    </div>
    <div> 
       <%= hidden_field_tag(:event_id, @event.id) %>
       <%= f.submit 'Upload', class: "btn btn-primary", controller: 'events', action: 'image_upload'%>
    </div>
<% end %>

现在,如果我上传文件,那么它可以顺利运行,但是当我提交它而不上传文件时。它没有显示验证错误。它给出了错误

param is missing or the value is empty: gallary

我的gallary params

def gallary_params
    params.require(:gallary).permit(:image, :event_id)
end

我的image_upload操作是

def image_upload
    @event = Event.find(params[:event_id])
    @gallary = @event.gallaries.build(gallary_params)
    if @gallary.save
        flash[:success] = "Image uploaded"
        redirect_to controller: 'events', action: 'event_info', id: @event.id
    else
        flash[:danger] = "error while uploading image"
        redirect_to controller: 'events', action: 'submit_solution', id: @event.id
    end
end

任何人都可以告诉我为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

试试这个:

<%= form_for @gallary do |f| %>
  <%= render 'shared/error_messages', object: @gallary %>

  <div class="field">
   <%= f.label :image %><br>
   <%= f.file_field :image %>
  </div>
 <div> 
   <%= f.hidden_field :event_id, :value => @event.id %>
   <%= f.submit 'Upload', class: "btn btn-primary", controller: 'events', action: 'image_upload'%>
  </div>
<% end %>

然后:

def image_upload
  @event = Event.find(params[:gallary][:event_id])
  @gallary = @event.gallaries.build(gallary_params)
  if @gallary.save
    flash[:success] = "Image uploaded"
    redirect_to controller: 'events', action: 'event_info', id: @event.id
  else
    flash[:danger] = "error while uploading image"
    redirect_to controller: 'events', action: 'submit_solution', id: @event.id
  end
end