让我的嵌套资源在Rails 4中工作

时间:2014-01-21 17:20:59

标签: ruby-on-rails-4

似乎无法弄清楚问题在这里。所以我有一个has_many条目的日志模型。在我的路线中,我把它设置为:

resources :logs, shallow: true do
  resources :entries
end

resources :entries

1)我是否需要底部的单独条目资源?这似乎与我使用的表格有关。

在我的日志部分中,我有一个表,然后使用底部的链接呈现部分条目以创建新条目:

<tbody>
  <%= render(log.entries) %>
</tbody>

<%= link_to 'New Entry', new_log_entry_path(@log) %>

条目/ _form.html.erb如下所示:

<%= form_for(@entry) do |f| %>

  <%= f.hidden_field :log_id %>

  <div class="field">
    <%= f.label :date %><br>
    <%= f.date_select :date %>
  </div>
  <div class="field">
    <%= f.label :name %><br>
    <%= f.select(:name, [['Bench Press', 1], ['Military Press', 2], ['Squat', 3], ['Deadlift', 4], ['Barbell Row', 5]]) %>
  </div>

  ...
  ...

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

最后,我的控制器代码,我有一个名为CurrentLog的问题:

module CurrentLog
  extend ActiveSupport::Concern

  private

    def set_log 
      @log = Log.find(params[:log_id])
    end
end

在我的参赛作品中,其开头是:

class EntriesController < ApplicationController
  include CurrentLog
  before_action :set_log
  before_action :set_entry, only: [:show, :edit, :update, :destroy]

  # GET /entries
  # GET /entries.json
  def index
    @entries = Entry.all
  end

  # GET /entries/1
  # GET /entries/1.json
  def show
    @entry = Entry.new
  end

  # GET /entries/new
  def new
    @entry = Entry.new(log_id: params[:log_id])
  end

  # GET /entries/1/edit
  def edit
  end

  # POST /entries
  # POST /entries.json
  def create
    @entry = Entry.new(entry_params)

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

现在的问题是:

当我创建,编辑或删除某个条目时,它与log_id(在本例中为1)与该条目不正确匹配。

使用表单创建新条目后,不是转到log / 1 / entries / xx,而是直接转到entries / xx,并且不从表单中携带适当的信息。我在这做错了什么?对不起,我希望我尽可能简洁!

1 个答案:

答案 0 :(得分:0)

没关系,我设法通过更改路线在link_tos中的某些位置来修复它。