简体   繁体   English

如何在Rails 5中提出两个模型的一对多关系视图

[英]How to come up with a view for one to many relation for two models in Rails 5

I'm trying to set up a one to many relationship between one model to another in rails, and it has worked in the console, but I can't seem to implement it properly in views so that I am able to create more pictures for a single event (more explained below) 我试图在Rails中建立一个模型与另一个模型之间的一对多关系,并且该模型已在控制台中运行,但是我似乎无法在视图中正确实现它,因此我可以为单个事件(下面有更多解释)

The background of the web application is, a single event has many event pictures, and many event pictures belong to a single event. Web应用程序的背景是,单个事件具有许多事件图片,并且许多事件图片都属于单个事件。 I'm trying to set this up properly within the console and schematics, it seems to have worked. 我正在尝试在控制台和原理图中正确设置它,似乎已经奏效了。 I was unable to get it working when I tried implementing it with views. 当我尝试使用视图实现它时,我无法使其工作。

    <%= form_with(model: [ @event, @event.event_pictures.build ], local: true) do |form| %>
  <p>
    <%= form.label :answer %><br>
    <%= form.text_field :answer %>
  </p>
  <p>
    <%= form.label :hint %><br>
    <%= form.text_field :hint %>
  </p>
  <p>
    <%= form.label :event_pics %>
    <%= form.file_field :event_pics, multiple: true %>
  </p>
  <p>
    <%= form.submit %>
  </p>
<% end %>

The code above is my form which is the main cause of the issue. 上面的代码是我的表格,这是导致此问题的主要原因。 The error is shown below. 错误如下所示。

undefined method `event_pictures' for nil:NilClass

Console stuff works.. in Pastebin ( https://pastebin.com/ESYAfMzE ) 控制台内容在Pastebin( https://pastebin.com/ESYAfMzE )中起作用。

Controller 调节器

def new
    render 'new'
  end
  def create
    @event = Event.find(params[:event_id])
    @event_picture = @event.event_pictures.create(event_picture_params)
    redirect_to event_path(@event_picture)
  end

**Button to create new picture, in Event Index, so you can see the event, before clicking on a button for a new picture. **用于在事件索引中创建新图片的按钮,因此您可以在单击新图片的按钮之前看到事件。 ** **

<%= button_to "new picture", {:controller => :event_picture, :action => 'new', :event_id => event.id},
              :method => :get,
              class: "btn btn-warning" %>

This is fairly frustrating as I've also looked into the possibility of using fields_for instead of form_with , and checked my schema.rb and migrations a number of times to make sure it is properly linked. 这相当令人沮丧,因为我也研究了使用fields_for而不是form_with的可能性,并检查了schema.rb并进行了多次迁移以确保其正确链接。 At this point, I'd really appreciate any help at all as I've gone hours looking at this problem. 在这一点上,我非常感谢任何帮助,因为我已经花了很多时间研究这个问题。

Thank you very much. 非常感谢你。

I see, in your new action, you need to setup the @event instance variable: 我看到,在您的new操作中,您需要设置@event实例变量:

def new
  @event = Event.find(params[:event_id])
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM