Как передать параметры вложенным атрибутам в форме fields_for в rails 5 с помощью скрепки

Недвижимость имеет несколько фотографий. Изображения, загруженные в форму, должны быть доступны через класс Property.

//Picture Model
class Picture < ApplicationRecord
  belongs_to :property
  has_attached_file :image, styles: { medium: "300x300>", thumb:"100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end

//Property Model
class Property < ApplicationRecord
  has_many :pictures, dependent: :destroy
  accepts_nested_attributes_for :pictures
end

//Form
<%= form_for @property, :html => {multipart: true} do |f| %>
  <%= f.fields_for :pictures do |ph| %>
    <%= ph.file_field :image, as: :file %>
  <% end%>
<% end%>

//Properties Controller
def new
  @property = Property.new
  @property.pictures.build
end

def create
  @property = current_user.properties.build(property_params)
  @property.seller = User.find(current_user.id) # links user to property via. user_id
  respond_to do |format|
    if @property.save
      format.html { redirect_to @property, notice: 'Property was successfully created.' }
      format.json { render action: 'show', status: :created, location: @property }
    else
      format.html { render action: 'new' }
      format.json { render json: @property.errors, status: :unprocessable_entity }
    end
  end
end

Ошибка при отправке формы: свойство Pictures должно существовать

1 ответ

В Rails 5 для автоматического присутствия Можете добавить optional: true к кому принадлежат:

class Picture < ApplicationRecord
  belongs_to :property, optional: true
end

Или вы должны сохранить свойство, прежде чем создавать изображение:

РЕДАКТИРОВАТЬ: простой способ сохранить свойство перед созданием изображения

# PropertyController
def create
  @property = current_user.properties.build(property_params)
  @property.seller = User.find(current_user.id) # links user to property via. user_id
  respond_to do |format|
    if @property.save
      @property.picture.create(picture_params)
      format.html { redirect_to @property, notice: 'Property was successfully created.' }
      format.json { render action: 'show', status: :created, location: @property }
    else
      format.html { render action: 'new' }
      format.json { render json: @property.errors, status: :unprocessable_entity }
    end
  end
end

def picture_params
    params.require(:property).permit(:picture)
end