且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

rails小重构:将图片加入产品Model

更新时间:2022-08-13 12:04:21

原先的产品product模式中存放的是图片的url,必须手动将图片存入指定目录中.现在略作改动,在数据库中新建一个pictures表,其设定如下:

class CreatePictures < ActiveRecord::Migration
  def change
    create_table :pictures do |t|
      t.integer :product_id
      t.string :name
      t.string :comment
      t.string :content_type
      t.binary :data,limit:1.megabyte

      t.timestamps null: false
    end
  end
end

同时配置picture和product的关系,让product has_one picture,让picture belongs_to product.然后修改product以前的image_url的验证模式:
1.删除其必须存在的验证
2.在其Regexp的验证中加入allow_blank:true

在product中加入after_save钩子和pic_tmp虚拟属性:

attr_accessor :pic_tmp
after_save :link_picture
def link_picture
        if pic_tmp
            pic = Picture.new
            pic.uploaded_picture(pic_tmp)
            self.picture = pic
        end
    end

以便在product保存中同时更新picture中与product对应的关系.

最后修改视图中的界面:

<%= form_for(@product,html:{multipart:true}) do |f| %>

  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_area :description,rows:6 %>
  </div>

  <div class="field">
    <%= f.label :image_url %><br>

    <% if @in_new %>
      <%= f.file_field("pic_tmp") %>
    <% else %>
      <% if @product.picture %>
        <%= f.file_field("pic_tmp") %>
      <% else %>
        <%= f.text_field :image_url %>
      <% end %>
    <% end %>
  </div>