Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 以一种形式创建两个模型_Ruby On Rails_View_Model - Fatal编程技术网

Ruby on rails 以一种形式创建两个模型

Ruby on rails 以一种形式创建两个模型,ruby-on-rails,view,model,Ruby On Rails,View,Model,这是我的代码示例: <%= form_for [@facility, @owner],:html => {:multipart => true} do |f| %> <%= render 'shared/error_messages_doc' %> <table> <tr> <td valign=top> First Name </td> <td &g

这是我的代码示例:

    <%= form_for [@facility, @owner],:html => {:multipart => true} do |f| %>
    <%= render 'shared/error_messages_doc' %>
    <table>
    <tr>
      <td valign=top> First Name </td>
      <td ><%= f.text_field :first_name %></td>
    </tr>
    <tr>
      <td valign=top> Last Name </td>
      <td ><%= f.text_field :last_name %></td>
    </tr>
    </table>
    <br>

    <table width = "750">
    <tr>
      <th>Day</th>
      <th>Start time</th>
      <th>End time</th>
    </tr>
    
    <%= f.fields_for :working_hours, @owner.working_hours do |wh| %>
    <div>
    <tr>
      <td><%= wh.object.week_day %></td>
      <td>
        <center><%= wh.text_field :start_time, :value => wh.object.start_time.strftime('%H:%M'), :style => "width: 100px;" %></center>
      </td>
      <td>
        <center><%= wh.text_field :end_time, :value => wh.object.end_time.strftime('%H:%M'), :style => "width: 100px;" %></center>
      </td>
    </tr>
    </div>
    <% end %>
  </table>
    <tr>
    <td><%= f.submit :class => "btn btn-primary" %></td>
    </tr>
    </table>
    <% end %>
{:multipart=>true}do | f |%>
名字
姓

白天 开始时间 结束时间 wh.object.start\u time.strftime(“%H:%M”),:style=>“宽度:100px;”%> wh.object.end_time.strftime(“%H:%M”),:style=>“宽度:100px;”%> “btn btn主要”%>

正如您所见,我正在尝试创建一个拥有大量工作时间(7个工作时间,每个工作日一个)的所有者。问题是,这是与编辑一起工作,但在我尝试创建新所有者时,工作时间字段不会显示。我认为问题在于@owner.working_hours正在从所有者那里寻找工作时间,而这在目前并不存在。因为我正在创建一个新的所有者,所以我需要为所有者创建一个7个工作小时的数组。如何执行此操作?

要创建
工作时间
请使用
build
。在控制器中,您可能需要以下内容:

class OwnersController < ApplicationController
  def new
    @owner = Owner.new
    @owner.working_hours.build(Time::DAYS_INTO_WEEK.map{|name, value| { day_of_week: value }})
  end
end

如您所见,它正在创建七个对象,设置了
day\u of\u week
属性。

感谢您的回复。我在控制器的新方法中添加了这条线,但它似乎没有创建七个对象。我把它放在我的视图中,但它只显示[],这是一个空数组。不寻常的是,它对我来说工作得非常好。您是否在
owners.rb
中有
接受\u嵌套的\u属性\u:working\u hours
?另外,
应该足够了。是的,我的owners.rb中有
@owner.working_hours.build([{:day_of_week=>0}, {:day_of_week=>1}, {:day_of_week=>2}, {:day_of_week=>3}, {:day_of_week=>4}, {:day_of_week=>5}, {:day_of_week=>6}])