【问题标题】:Rails Nested Fields Nil but still show in viewRails Nested Fields Nil 但仍显示在视图中
【发布时间】:2015-10-04 01:38:19
【问题描述】:

我试图在表单中显示嵌套属性,即使嵌套属性为 nil。例如

<%= f.fields_for :package_survey_image do |image_form|%>
  <% if PackageSurvey::Image.where(id:f.object[:package_survey_image_id]).count != 0 %>
        <%= image_tag PackageSurvey::Image.find(f.object[:package_survey_image_id]).logo.url(:medium) %>
  <% end %>
        <%= image_form.file_field :logo %>
<%end %>

因此,如果 package_survey_image 为 nil 或为空,我希望视图显示一个浏览按钮来上传图像。我不想在控制器中实例化 package_survey_image。

【问题讨论】:

    标签: ruby-on-rails forms nested


    【解决方案1】:

    即使您不想在控制器中实例化它,也应该这样做。我会在控制器中执行以下操作:

    @obj.image.build if @obj.image.blank?
    

    然后在视图中:

    <%= f.fields_for :package_survey_image do |image_form|%>
    <%= image_form.file_field :logo %>
    <% end %>
    
    <% if @obj.package_survey_image %>
    # Display the image. 
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 2011-06-23
      • 1970-01-01
      • 2011-04-02
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-25
      • 2018-04-10
      • 2017-05-18
      相关资源
      最近更新 更多