新手问题 关于 kindeditor 存 附件信息到数据库的问题

luoyi · August 29, 2016 · Last by luoyi replied at September 01, 2016 · 2083 hits

gem 使用的是 @macrow https://github.com/Macrow/rails_kindeditor 的插件,使用的过程中对附件信息存数据库部分有点不懂,代码如下: 在控制器里我的代码是这样的:

def new
  @article = Article.new()
end

这样在新建文章的模板里面

article.id

肯定是空的,然后我就用了下面的代码实现了这个,不过不知道这样做对不对,有没有更好的方法。

def new
  lastarticle = Article.last
  ownerid = lastarticle.id + 1
  @article = Article.new(id: ownerid)
end

非常感谢您 @macrow 提供这么好用的插件,之前用别的折腾了好久都没有弄好。

1.owner 可不填,但是就不能关联删除了。 2.owner 可用 article 的 owner,如 user

#1 楼 @chen_rb 用 user 的话,删除文章应该就不能关联删除文章相关的附件了吧?刚刚遇到个新的问题,还要请教下您。 这里,使用 asset.asset 按说应该获取到的是附件名称,但是测试获取出来的是下面的内容,其他的字段获取都是正常的。

2.3.0 :065 > asset.asset
 => #<Kindeditor::AssetUploader:0x0000000543b700 @model=#<Kindeditor::Asset id: 2, asset: "13b6a71d218b.png", file_size: 16877, file_type: "image/png", owner_id: 2, owner_type: "Article", asset_type: "image", created_at: "2016-08-29 12:50:39", updated_at: "2016-08-29 12:50:39">, @mounted_as=:asset, @storage=#<CarrierWave::Storage::File:0x0000000543b480 @uploader=#<Kindeditor::AssetUploader:0x0000000543b700 ...>>, @file=#<CarrierWave::SanitizedFile:0x00000005383e70 @file="/home/roy/web/dev/xcy/public/uploads/image/201608/13b6a71d218b.png", @original_filename=nil, @content_type=nil>, @versions={}> 

相应的数据表

1.用 user 的话,删除文章附件应该不会删除。但其实很多附件应该是需要各个文章复用的。比如说图片之类的。 2.asset.asset 获取到的应该是一个 asset 对象。to_s 之后就是路径

#3 楼 @chen_rb 图片是有复用的情况,主要是怕时间长了产生大量不用的图片占据存储空间。to_s 之后确实获取到了,回头看看插件源码再理解下。谢谢您👍

使用下面的方法实现,可能会出现第一个人在编辑还未保存的情况下,第二人也在创建并先保存了。owner 会指向同一个 id。

def new
  lastarticle = Article.last
  ownerid = lastarticle.id + 1
  @article = Article.new(id: ownerid)
end

可以先把@article保存。

def new
  @article = Article.new()
  @article.published = false #可以加一个字段用于排除预先保存的内容,在show中使用。
  @article.save
end

然后在 view 中直接使用。

<%= f.kindeditor :content, :owner => @article %>

#5 楼 @gxlonline 👍 谢谢您的提醒和帮助,不然不知道什么时候才会发现这个问题。

You need to Sign in before reply, if you don't have an account, please Sign up first.