原谅我。我在拉斯维加斯,必须是愚蠢的。Rails用关联对象更新现有对象
我有许多附件的文章模型。属于文章的附件模型。所以,如果我创建一篇没有附件的文章,那么我想编辑它并添加一个我感兴趣的附件。
当我的文章编辑操作是这样的:
def edit
end
当我更新我的带有附件的文章,这是行不通的。但是,当我用空名称和空白内容更新我的文章时,我打破了我期望的模型中设置的验证。当我这样做时,这是params散列。
Parameters: {"utf8"=>"✓","authenticity_token"=>"1X8Jr3Om2lrnhNEojTppKGRpRwF8/fidVHdC+H4UMPkAiF/oPF9yxB6j0jfL/I7VzUcDtTIh2iB+B7b19XN2Ug==", "article"=>{"name"=>"", "content"=>""}, "commit"=>"Update article", "business_id"=>"1", "id"=>"43"}
现在,当我改变我的编辑操作这样的:
def edit
@article.attachments.build
end
当我和附件更新了一篇文章,我把它和它的作品。但我的验证不再检查。当我提交一个空名称和散列的票据时,它只是返回到显示页面,就像更新,保留现有数据。
我想知道为什么。
这里是我的PARAMS哈希当我做这与上面的编辑动作:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"SQon3+gX/5vg9HKTUr/hWgRAagHIrA2PYexrq6Umasqc/XGYp+5XBRnTcYwUeQanrW4utYZwLzJLnJ+mLkEsYQ==", "commit"=>"Update article", "business_id"=>"1", "id"=>"43"}
注意,PARAMS [:文章]因为它在第一个不存在这里,这是为什么,明明,验证将被跳过。我的问题是,为什么?
我不认为这会很难,所以我责怪拉斯维加斯:)。
更新与观点:
附件/ _form如果我叫建立在一个新的或编辑的文章,除非版本是在编辑上不存在编辑,但我可以单击JS其存在,但在该情况下链接到附件的新动作的按钮。
<%= f.simple_fields_for :attachments, child_index: index do |ff| %>
<%= ff.input :file, as: :file, label: "File ##{index += 1}" %>
<%= ff.input :file_cache, as: :hidden %>
<% end %>
下面是文章的形式:
<%= simple_form_for([@business, @article]) do |f| %>
<%= f.input :name %>
<%= f.input :content %>
<%= f.error :content_count, class: "alert-error" %>
<div id="attachments">
<h3>Attachments</h3>
<% index = 0 %>
<%= render partial: "attachments/form", locals: { f: f, index: 0 } %>
</div>
<p>
<% if [email protected]? %>
<%= link_to "Add another file", new_attachment_path, remote: true,
id: "add_file", data: { params: {index: @article.attachments.size} } %>
<% else %>
<%= link_to "Add another file", edit_attachment_path, remote: true,
id: "add_file", data: { params: {index: @article.attachments.size} } %>
<% end %>
</p>
<%= f.button :submit, class: "btn-primary" %>
我尝试添加的,如果在这里case语句我可以把这个请求在附件控制器不同的“动作”,但它只是复制这个问题,并没有纠正它,所以你可以忽略,因为我会删除它。
这里是附件控制器,但:
def new
@index = params[:index].to_i
@article = Article.new
@article.attachments.build
render layout: false
end
def edit
@index = params[:index].to_i
@article = Article.find(params[:id])
@article.attachments.build
render layout: false
end
还有一个编辑添加JS:
ready = ->
$("#add_file").on "ajax:success", (event, data) ->
$("#attachments").append data
$(this).data "params", { index: $("#attachments div.file").length }
证明生成编辑页面视图(S)。 – smathy
按要求添加。我也可以添加更多。 :)。我也尝试过在视图中使用不同的东西,但这只是重复了这个问题。有是创建表单字段,当我点击它是由轨道4在行动提供一个基础标准的东西的链接JS代码。 – Art
你是否在嵌套参数?您是否将文章控制器中的参数列入白名单?我会删除该构建。我会专注于让他们传递参数散列。然后使用参数中的附件从文章更新操作创建附件。 – toddmetheny