0

Доброго дня. Делаю небольшой проект, столкнулся с проблемой не сохранения фотографий.

Мои модели:

class Arendakvartir < ActiveRecord::Base

 has_many :attachments, dependent: :destroy
 accepts_nested_attributes_for :attachments
 validates_associated :attachments

end

class Attachment < ActiveRecord::Base


  belongs_to :arendakvartir

  has_attached_file :image,
                    :path => ":rails_root/public/images/:id/:filename",
                    :url  => "/images/:id/:filename",
                    styles: { medium: "300x300>", thumb: "100x100>" }

  validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
 validates_attachment :image, presence: true
  validates_attachment_size :image, :less_than => 5.megabytes

end

Контроллер:

class ArendakvartirsController < ApplicationController

  def new
    @arenda = Arendakvartir.new()
  end

  def show

  end


  def create
 # binding.pry
    @arenda = Arendakvartir.new()
    @arenda.attachments.build()

    if @arenda.save(arenda_params)
      respond_to do |format|
          flash[:positive] = "Объект сохранен успешно"
          format.html { redirect_to new_arendakvartir_path }
      end
    else
      respond_to do |format|
          flash[:negative] =  "Объект не был сохранен успешно"
          format.html { render action: 'new'}
     end
   end
end
  private

  def arenda_params

    params.require(:arendakvartir).permit(:attachments_attributes =[:image]

    )
  end


end

Форма с предложением:

<%= nested_form_for(@arenda, :html =>  { :class => "ui form", :id => "create_new_arenda", :multipart => true }) do |t| %>

        <%= render 'shared/errors', :obj => @arenda  %>

          <%= t.fields_for :attachments do |a| %>
              <%= a.file_field :image, :name => 'arendakvartir[attachments_attributes][][image]' %>
          <% end %>



<%= submit_tag("Добавить объект", :class => "ui huge olive button") %>

<% end %>

В конечном итоге получаю ошибку валидации модели Attachment

В форме присутствуют ошибки:

Attachments image can't be blank Attachments is invalid

Подскажите где же я тут не прав. Мой gemfile:

source 'https://rubygems.org'

gem 'pg'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.3'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'paperclip', '~> 4.3'
#gem 'rmagick', '~> 2.15', '>= 2.15.4'
#Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
gem "wysiwyg-rails"
gem "font-awesome-rails"
gem "nested_form"
gem 'semantic-ui-sass', github: 'doabit/semantic-ui-sass'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'

  gem 'pry'

  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'

  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
end

1 ответ 1

1

Хэшмап с атрибутами есть смысл передавать в следующие методы модели:

  • new (build для ассоциации)
  • create
  • assign_attributes
  • update_attributes (+ алиас update)

...но не в save, который отвечает исключительно за запись текущего состояния объекта в БД.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.