这次做新项目的时候,把图片都放在了一个表里,其他表中不再存图片信息,通过多态关联建立表之间的关系。

(1)新建picture表, component表不需要处理

class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.integer :imageable_id
t.string :imageable_type
t.string :name
t.string :md5
t.string :url
t.timestamps
end add_index :pictures, [:imageable_type, :imageable_id]
end
end

(2)关于model的关联

多态关联的文档 http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

A slightly more advanced twist on associations is the polymorphic association.

With polymorphic associations, a model can belong to more than one other model, on a single association.

For example, you might have a picture model that belongs to either an employee model or a product model.

Here's how this could be declared:

class Component < ApplicationRecord
serialize :hints, Hash has_many :pictures, as: :imageable
accepts_nested_attributes_for :pictures, reject_if: proc { |attributes| attributes['md5'].blank? || attributes['url'].blank? }
end
class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true end

对下拉框的处理

  PICTURE_NAME = {
'海报图' => 'poster',
'背景' => 'background',
'左下角角标' => 'left_bottom_corner',
'右下角角标' => 'right_bottom_corner',
'左上角角标' => 'left_top_corner',
'右上角角标' => 'right_top_corner'
} def picture_name picture_name
PICTURE_NAME.invert[picture_name]
end

关于多态关联的Instance Public methods: http://api.rubyonrails.org/

accepts_nested_attributes_for(*attr_names)Link

Defines an attributes writer for the specified association(s).

Supported options:

:allow_destroy

If true, destroys any members from the attributes hash with a _destroy key and a value that evaluates to true(eg. 1, '1', true, or 'true'). This option is off by default.

:reject_if

Allows you to specify a Proc or a Symbol pointing to a method that checks whether a record should be built for a certain attribute hash.

The hash is passed to the supplied Proc or the method and it should return either true orfalse. When no :reject_if is specified,

a record will be built for all attribute hashes that do not have a _destroyvalue that evaluates to true.

Passing :all_blank instead of a Proc will create a proc that will reject a record where all the attributes are blank excluding any value for _destroy.

:limit

Allows you to specify the maximum number of associated records that can be processed with the nested attributes.

Limit also can be specified as a Proc or a Symbol pointing to a method that should return a number.

If the size of the nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecordsexception is raised.

If omitted, any number of associations can be processed.

Note that the :limit option is only applicable to one-to-many associations.

:update_only

For a one-to-one association, this option allows you to specify how nested attributes are going to be used when an associated record already exists.

In general, an existing record may either be updated with the new set of attribute values or be replaced by a wholly new record containing those values.

By default the :update_onlyoption is false and the nested attributes are used to update the existing record only if they include the record's:id value.

Otherwise a new record will be instantiated and used to replace the existing one.

However if the:update_only option is true, the nested attributes are used to update the record's attributes always,

regardless of whether the :id is present. The option is ignored for collection associations.

Examples:

# creates avatar_attributes=
accepts_nested_attributes_for :avatar, reject_if: proc { |attributes| attributes['name'].blank? }
# creates avatar_attributes=
accepts_nested_attributes_for :avatar, reject_if: :all_blank
# creates avatar_attributes= and posts_attributes=
accepts_nested_attributes_for :avatar, :posts, allow_destroy: true
 
 http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
如果在编辑或者新建component的时候,传的picture相关的参数里带有id,那么这条图片记录会被修改,不会被新建。

If the hash contains an id key that matches an already associated record, the matching record will be modified:

member.attributes = {
name: 'Joe',
posts_attributes: [
{ id: 1, title: '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
{ id: 2, title: '[UPDATED] other post' }
]
} member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
member.posts.second.title # => '[UPDATED] other post'

(3)controller里的处理

Nested Parameters

http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters

  private
def set_component
@component = Component.find(params[:id])
end def component_params
params.require(:component).permit(:release_id,
:unitary, {pictures_attributes: [:id, :imageable_type, :imageable_id, :name, :url, :md5]},
:remark, component_ids: [], hints: [:left, :mid, :right]
)
end

(4)_form里的处理

  <div class="image-group">
<% @component.pictures.each do |p| %>
<%= hidden_field_tag 'component[pictures_attributes][][id]', p.id %>
<div class="form-group">
<%= f.label 'name', class: 'col-sm-2 control-label' %>
<div class="col-sm-4">
<%= text_field_tag 'component[pictures_attributes][][name]', @component.picture_name(p.name), class: 'form-control' %>
</div>
</div> <div class="form-group">
<%= f.label 'md5', class: 'col-sm-2 control-label' %>
<div class="col-sm-4">
<%= text_field_tag 'component[pictures_attributes][][md5]', p.md5, class: 'form-control' %>
</div>
</div> <div class="form-group">
<%= f.label 'url', class: 'col-sm-2 control-label' %>
<div class="col-sm-4">
<%= image_tag p.url, :width => 300 %><br/>
</div>
<div class="col-sm-4">
<%= text_field_tag 'component[pictures_attributes][][url]', p.url, class: 'form-control' %>
</div>
</div>
<% end %>
</div>

polymorphic-associations 多态关联实例 ruby on rails的更多相关文章

  1. Windows下: RubyMine + Ruby On Rails + mysql 搭建开发环境

    最近在接手一个手机项目.在搭建环境的过程中,遇到了一些问题,在下文中已做记录,并奉上个人的解决方案. 开发环境 win2003 ;  JetBrains RubyMine6.3.3 1.  下载最新版 ...

  2. [ruby on rails] 跟我学之(8)修改数据

    修改views 修改index视图(app/views/posts/index.html.erb),添加编辑链接,如下: <h1>Our blogs</h1> <% @p ...

  3. [ruby on rails] 跟我学之(3)基于rails console的查增删改操作

    本章节展开对model的介绍:包括查增删改操作.紧接着上面一节<[ruby on rails] 跟我学之HelloWorld> 创建模型 使用命令创建模型 创建表post,默认自带两栏位 ...

  4. [Ruby on Rails系列]6、一个简单的暗语生成器与解释器(上)

    [0]Ruby on Rails 系列回顾 [Ruby on Rails系列]1.开发环境准备:Vmware和Linux的安装 [Ruby on Rails系列]2.开发环境准备:Ruby on Ra ...

  5. laravel的多态关联--morphTo和morphMany

    首先,文档里面讲述的不是特别详细,详细寻找查询流程没有过多介绍,只是介绍如何去定义,直接使用,导致很多该明白的东西,没有说明,下面详细看看这个多态关联 是怎么定义,使用,详细查询的. 先看文档介绍 多 ...

  6. Ruby on Rails 實戰聖經阅读(三)

    由于是1.8.x:圣经的1.9.3差太多,所以另外按1.8.X来创建hello world 第一個Hello World!! 1. 创建项目rails -d mysql first 2.创建控制器  ...

  7. [技术博客] 软工-Ruby on Rails 后端开发总结分享

    [技术博客] 软工-Ruby on Rails 后端开发总结分享 在这次软件编写中,我们的后端使用了Ruby on Rails (RoR)框架. Rails框架是用Ruby编写的.这意味着当我们为Ru ...

  8. Linux超快速安装Ruby on Rails

    Linux超快速安装Ruby on Rails 时间 2014-11-25 11:45:11 Flincllck Talk 原文  http://www.flincllck.com/quick-ins ...

  9. 管理不同版本ruby和rails的利器——rvm

    近年来,ruby on rails逐渐火了起来,我想各位码农早就耳闻,特别是那些做B/S项目的童鞋,早就想跃跃一试了. 笔者也是初次接触ruby on rails ,我想,对于初学者来说,最好的学习方 ...

随机推荐

  1. CSS3定位和浮动详解

    本文为大家分享CSS3定位和浮动的基础概念,与使用方法,供大家参考,具体内容如下 一.定位 1. css定位: 改变元素在页面上的位置 2. css定位机制: 普通流: 浮动: 绝对布局: 3. cs ...

  2. asp.net与Matlab类型转换(待补全)

    上上篇的博客已经提到如何配置环境,即如何在asp.net中调用matlab生成的dll文件.这篇博客打算做个笔记,那就是matlab和C#数据类型如何转换.随着需求的增加,我会不断增加新的类型转换. ...

  3. phpcms v9 数据库操作函数

    表明默认当前load_model('xxxx')模块所在表名xxxx 若要指定表名  则:操作在mysql.class.php中$this->db->select(...) 1.查询  $ ...

  4. 自然语言19.1_Lemmatizing with NLTK(单词变体还原)

    QQ:231469242 欢迎喜欢nltk朋友交流 https://www.pythonprogramming.net/lemmatizing-nltk-tutorial/?completed=/na ...

  5. Spring MVC学习笔记——JSR303介绍及最佳实践

    JSR 303 – Bean Validation 是一个数据验证的规范,2009 年 11 月确定最终方案.2009 年 12 月 Java EE 6 发布,Bean Validation 作为一个 ...

  6. JavaWeb学习笔记——JSP标准标签库JSTL

  7. Java排序算法——选择排序

    import java.util.Arrays; //================================================= // File Name : Select_S ...

  8. HTML学习笔记——块级标签、行级标签、图片标签

    1>块级标签.行级标签 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "htt ...

  9. 以全局监听的方式处理img的error事件

    http://www.ovaldi.org/2015/09/11/%E4%BB%A5%E5%85%A8%E5%B1%80%E7%9B%91%E5%90%AC%E7%9A%84%E6%96%B9%E5% ...

  10. Python 开发与测试 Webservice(SOAP)

    WebService是一种跨编程语言和跨操作系统平台的远程调用技术. 理解WebService 1.从表面上看,WebService就是一个应用程序向外界暴露出一个能通过Web进行调用的API,也就是 ...