【问题标题】:How to pass params to nested attributes in fields_for form in rails 5 with paperclip如何使用回形针将参数传递给rails 5中fields_for表单中的嵌套属性
【发布时间】:2017-06-18 02:01:06
【问题描述】:

一个属性有多个图片。表单中上传的图片应该可以通过 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

提交表单时收到错误:图片属性必须存在

【问题讨论】:

    标签: ruby-on-rails paperclip ruby-on-rails-5 nested-attributes accepts-nested-attributes


    【解决方案1】:

    在 Rails 5 中,belongs_to 会自动验证是否存在。您可以将optional: true 添加到belongs_to:

    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
    

    【讨论】:

    • 对,如果我这样做,那么他们就不会链接。我如何在图片之前保存属性?
    • 你看,在图片中使用belongs_to :property表示你会保存property_id em图片,所以必须先保存property!一个简单的方法是:在@property.save之后你可以做@property.pictures.create(picture_params)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2018-04-23
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多