【问题标题】:How to use link_to inside a nested form in Rails?如何在 Rails 的嵌套表单中使用 link_to?
【发布时间】:2013-03-26 23:03:40
【问题描述】:

我有一个可能包含许多文件的对象的嵌套表单。我在创建对象时没有问题,但是当我需要编辑它时,我发现了问题,表单应该有文件 url 的链接,但我不知道如何引用文件本身。我用回形针。在这种情况下,如果只有一个文件并且它在对象模型中,我会做类似@object.file.url 但由于文件很多,我不知道在这种情况下如何进行......

edit.html.haml

= form_for @object, :url => { :action => "update", :controller => "object", :id => @object.id, :method => "post" }, :html => { :multipart => true }  do |f|

  - render "object/object_form", object: f.object, f: f

object_form.html.haml

.field
  = f.label :name
  = f.text_field :name

= f.fields_for :files do |builder|
  = render 'object/file_fields', :f => builder
%p= link_to_add_fields "Add new file", f, :file

.field
  = f.submit "Save"

file_fields.html.haml

%fieldset
  .field
    = f.label :file
    = f.file_field :file
  .field
    = f.hidden_field :_destroy
    = link_to "Remove File", '#', class: "remove_fields"

我正在尝试做的显然不适用于 file_fields.html.haml

%fieldset
  .field
    = f.label :file
    = f.file_field :file
    = link_to f.file.url 
  .field
    = f.hidden_field :_destroy
    = link_to "Remove File", '#', class: "remove_fields"

【问题讨论】:

    标签: ruby-on-rails paperclip nested-forms nested-attributes


    【解决方案1】:

    我认为你应该可以做到

    f.object.url
    

    所以:

    %fieldset
      .field
        = f.label :file
        = f.file_field :file
        # Not sure if it would produce a Nil error on the new form.
        # given how the f object wouldn't yet have a url
        - if f.object.url
           = link_to f.object.url 
      .field
        = f.hidden_field :_destroy
        = link_to "Remove File", '#', class: "remove_fields"
    

    【讨论】:

    • 谢谢,你是对的...... f.object 成功了,但是,获取 url 是 f.object.file.url! =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多