【问题标题】:Rails 3.2 - Nested Resource Passing IDRails 3.2 - 嵌套资源传递 ID
【发布时间】:2012-03-07 21:05:39
【问题描述】:

好的,我的联想是:

Outlet -> has_many :monitorings
Monitoring -> belongs_to :outlet

我的路线:

resources :outlets do
   resources :monitorings
end

查看:

<%= link_to new_outlet_monitoring_path(@outlet) %>

当我单击链接时,日志显示 outlet_id 作为参数正确传递到新页面。 但是在保存监控记录的时候,outlet_id变成了nil。

有什么帮助吗?

更新:

# views/monitorings/_form.html.erb  

<%= form_for(@monitoring) do |f| %>
<h2>Type of Monitoring</h2>
<fieldset data-role="controlgroup" >
    <div class="radio-group">
      <%= f.radio_button :mtype, "Full" %><%= f.label :mtype, "Full", value: "Full" %>
      <%= f.radio_button :mtype, "Partial" %><%= f.label :mtype, "Partial", value: "Partial" %>
      <%= f.radio_button :mtype, "None" %><%= f.label :mtype, "None", value: "None" %>
    </div>
</fieldset>
<hr>
<%= f.submit "Next Step" %>
<% end %>

还有控制器:

# controllers/monitoring_controller.rb  


def new
    @monitoring = Monitoring.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @monitoring }
    end
end

def create
  @monitoring = Monitoring.new(params[:monitoring])

  respond_to do |format|
    if @monitoring.save
      format.html { redirect_to @monitoring, notice: 'Monitoring was successfully created.' }
      format.json { render json: @monitoring, status: :created, location: @monitoring }
    else
      format.html { render action: "new" }
      format.json { render json: @monitoring.errors, status: :unprocessable_entity }
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails forms ruby-on-rails-3.2 nested-resources


    【解决方案1】:

    这很可能是您创建新监控记录的方式存在问题。我们可以看到您的表单和您的创建控制器操作吗?

    【讨论】:

    • 我已将其添加为对您原始问题的更新 :)
    • 有两种方法可以做到这一点。两者都涉及您在新的控制器操作中创建出口对象。所以将@outlet = Outlet.find(params[:outlet_id]) 添加到新操作中。现在你有两个选择。 1:将@monitoring 的声明更改为@monitoring = @outlet.monitorings.new,并且在您的视图中不做任何更改。 2:单独保留@monitoring 的声明并将您的form_for 更改为form_for [@outlet, @monitoring] do |f|
    • 我使用选项 2,之前没有尝试过选项 1。不过,我认为它会起作用。
    • 我已经尝试了这两种方法,但似乎无法使其正常工作。日志显示 outlet_id 已传递到 monitorings#new Parameters: {"outlet_id"=&gt;"2"},但是当创建操作运行时 outlet_id 保持为空。
    • outlet_id 将始终传递给 create 操作,因为您有一个看起来像 /outlets/:outlet_id/monitorings/ 的嵌套路由。您正在使用 params[:monitoring] 创建一个监控对象。这意味着您需要将出口 id 作为监控 [outlet_id] 传递。我给你的第二个选项应该自动执行。
    猜你喜欢
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多