带图像上传的嵌套属性

时间:2017-05-12 19:46:27

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

我有两种模式:

unsnoc

我想在我创建CAMPAIGN

的同一_form中创建一个QUESTION

CAMPAIGN CONTROLLER

class Campaign < ApplicationRecord
    has_many :questions
    validates_presence_of :name

    accepts_nested_attributes_for :questions
end


class Question < ApplicationRecord
    belongs_to :campaign
    has_many :answered_questions
    has_many :answers, through: :answered_questions


    has_attached_file :image, :storage => :cloudinary, :path => ':id/:style/:filename', styles: { medium: "300x300>", thumb: "100x100>" }
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/

    validates_presence_of :title, :image, :campaign_id

    validates_associated :campaign

    def image_url
        image.url(:thumb)
    end

end

运动/ _form.html.erb

    def new
        @campaign = Campaign.new
        @questions_builded = @campaign.questions.build
    end

    def create
        @campaign = Campaign.new(campaign_params)

        respond_to do |format|
          if @campaign.save
            format.html { redirect_to @campaign, notice: 'Campanha foi criada com sucesso' }
            format.json { render :show, status: :created, location: @campaign }
          else
            format.html { render :new }
            format.json { render json: @campaign.errors, status: :unprocessable_entity }
          end
        end
    end
private

        def campaign_params
            params.require(:campaign).permit(:name, :active, questions_attributes: [:id, :title, :image, :campaign_id])
        end

当我提交表单时,终端显示此错误并且未创建任何内容

<%= form_for @campaign, html: { multipart: true } do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %><br />

  <%= f.radio_button(:active, true) %>
  <%= f.label :active, 'Ativado', :value => true %>

  <%= f.radio_button(:active, false) %>
  <%= f.label :active, 'Desativado', :value => false %>

      <%= f.fields_for :questions, @questions_builded do |q| %>
        <%= q.label :title %>
        <%= q.text_field :title %><br />

        <%= q.label 'Imagem' %>
        <%= q.file_field :image %><br />
      <% end %>

  <%= f.submit %>
<% end %>

我使用宝石回形针和宝石'paperclip-cloudinary'来存储图像。

PS:问题/ _form.html.erb工作正常

1 个答案:

答案 0 :(得分:1)

回滚可能表示您尝试保存模型时模型无效。这是一个猜测,但也许它与validates_associated :campaign有关,因为广告系列在问题之后被保存了?

对于像这样的状态问题,我喜欢在日志中使用调试器或日志状态。例如,在尝试将模型保存在控制器中之前,可以添加一个日志语句来检查模型是否有效。

@campaign.valid?; logger.info(@campaign.errors.full_messages)