我正在使用 FileStack API 和 filepicker gem ( https://github.com/Ink/filepicker-rails )。我按照文档中使用 OnChange 访问 FilePicker 文件中概述的步骤进行操作。我试图获取 JSON 浏览器响应属性、文件名,通过路由将其传递到我的 Rails Controller ,并将其保存为我的附件模型中的 :name 。
附件/新 View
<%= filepicker_js_include_tag %>
<%= simple_form_for(@attachment) do |f| %>
<%= f.filepicker_field :title, multiple: 'true', onchange: 'onUpload(event)' %>
<%= f.submit %>
<% end %>
<script>
function onUpload(event) {
var name = event.fpfile.filename;
jQuery.ajax({
data: { "attachment[name]": name, "attachment[title]": url },
type: 'post',
url: "/attachments"
});
}
</script>
路线
post 'attachments/' => 'attachment#create'
附件 Controller
def create
@attachment = current_user.attachments.build(attachment_params)
if @attachment.save
redirect_to attachments_path
else
render root_path
end
end
...
private
def attachment_params
params.require(:attachment).permit(:title, :user_id, :name)
end
我浏览了相关的 SO 帖子,这就是我实现此实现的方式。但是,当我在 Rails 控制台中查看附件模型时,名称为零。我的数据没有正确传递。我不确定我是否遗漏了某个步骤或没有正确路由。任何建议将不胜感激。
最佳答案
你的 Controller super 困惑,删除其中大部分并保持简单,如下所示。这一行将涵盖您的 current_user.id
和 name
。
def create
@attachment = current_user.attachments.build(attachment_params)
if @attachment.save
redirect_to attachments_path
else
render root_path
end
end
此外,同时你有参数许可
params.require(:attachment).permit(:name, :title, :user_id)
您必须传递像这样的数据“attachment[name]”
,但您传递的是简单的“name”
。这就是获得Unpermissed argument: name
的原因。正如 @anonymousxxx 提到的,从路由中删除 :name
部分!!!
脚本
<script>
function onUpload(event) {
var name = event.fpfile.filename;
jQuery.ajax({
data: { "attachment[name]": name },
type: 'post',
url: "/attachments"
});
}
</script>
关于javascript - 将 JavaScript 变量保存到 Rails 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37265963/