Rails视图中的嵌套模型

问题描述 投票:0回答:2

如何在事件索引中正确嵌套事件图片,以便在发布event_pictures时可以查看它们?

这是我的模特

class EventPicture < ApplicationRecord
belongs_to :event
end

我正在以我的形式使用字段

 <%= f.fields_for :event_picture, @event.event_picture do |ff| %>

  <p>
    <%= ff.label :name  %><br>
    <%= ff.text_field :name %>
  </p>

  <p>
    <%=ff.label :url %>
    <%=ff.text_field :url %>
  </p>
  <% end %>

这是我的事件视图(索引):

<% if user_signed_in? %>
  <div class = "admincreate">
    <% if user_signed_in? %>
      <p> <button type="button" class="btn btn-primary"><%= link_to 'New event' , new_event_path(@events)%> </button> </p>
  </div>
<% end %>


    <% @events.each do |event| %>
      <% if user_signed_in? %>
        <div class =".btn-group-xs">
      <tr>
        <td> <button type="button" class="btn btn-primary"><%= link_to 'Show', event_path(event) %> </button>  </td>
        <td> <button type="button" class="btn btn-primary"><%= link_to 'Edit', edit_event_path(event) %> </button> </td>
        <td> <button type="button" class="btn btn-primary"><%= link_to 'Delete',event_path(event),
                      method: :delete,
                      data: { confirm: 'Are you sure?'} %> </button></td>
        </div>
      </tr>
      <% end %>
    <% end %>
</table>
<% end %>

<table>
<% @events.each do |event| %>
<tr>
        <td class = "content-overlap-right">
        <h1 class = "eventtitle"> <h1><%= event.title%> </h1>
        <p class = "eventlink"><b> <%= event.url %></b></p>
        <p class = "eventbody"><%= event.body%> </p>
        </td>
</tr>
<%end%>
</table>

这是我的控制器

def event_params
      params.require(:event).permit(:title, :url, :body, event_picture_attributes:
        [:id, :url, :name])
    end

我已经尝试了1)event_pictures.URL(在我的@events.each do中)并且我已经尝试了每个事件图片。

也许我错过了一个小细节或者已经离开了,但我对于一般显示嵌套属性有点困惑。

谢谢你的帮助!

编辑:我的最终目的是,当事件被删除时,关联的event_picture将被删除 - 以及每个发布的事件都会显示事件图片。我假设有一个@event_picture.each do参与,但它不是很直接的看似(当然,它必须是相关的事件图片)。

如果有人回答,我会尽力让其他人明白答案。

编辑: 这是我的routes.rb

resources :events do resources :event_pictures, shallow: true end

ruby-on-rails ruby nested
2个回答
0
投票

要显示活动的图片:

<%= image_tag event.event_picture.url ... %>

要在事件模型中销毁图片:

has_one :event_picture, :dependent => :destroy

0
投票

首先,如果您希望在销毁事件对象时销毁嵌套资源,请将:_delete添加到event_picture_attributes

要使嵌套资源正常工作,请使用rails表单构建器声明路由并创建表单。

请按照这些教程告诉我您是否遇到任何问题。

http://guides.rubyonrails.org/routing.html#nested-resources

http://guides.rubyonrails.org/form_helpers.html#nested-forms

© www.soinside.com 2019 - 2024. All rights reserved.