0

处理我的第一个应用程序,有点卡住了。我正在关注嵌套属性的修订版 railscast,但我的表单不显示字段。以下是我所拥有的。日期和提交字段都显示,但我试图为动作制作的字段(然后我需要一个用于代表和重量的字段)根本没有出现。就好像它在渲染时不存在一样。

/views/workouts/_workout_form.html.erb内容如下:

<%= form_for(@workout) do |f| %>
    <%= render 'common/form_errors', object: @workout %>

    <p>
        <%= date_select :workout, :workout_date %><br />

        <%= f.fields_for :exercises do |builder| %>
        <fieldset>
            <%= builder.label :movement, "Movement" %><br />
            <%= builder.text_area :movement %>
        </fieldset>
        <% end %>

    </p>

    <p>
        <%= f.submit "Log It" %>
    </p>


<% end %>

/views/workouts/index.html.erb内容如下:

<%= provide(:title, 'GymLog') %>

<div id='ask'>
<h1>Post a Workout</h1>
<% if logged_in? %>
<%= render 'workout_form' %>
<% else %>
<p>Please login</p>
<% end %>
</div>

/models/exercise.rb内容如下:

class Exercise < ActiveRecord::Base
  belongs_to :workout
  attr_accessible :movement, :reps, :weight
end

/models/workout.rb内容如下:

class Workout < ActiveRecord::Base
  belongs_to :user
  has_many :exercises
  attr_accessible :workout_date, :exercises_attributes
  accepts_nested_attributes_for :exercises
end

/controllers/workout_controller.rb内容如下:

class WorkoutsController < ApplicationController
  before_filter :auth, only: [:create]

  def index
    @workout = Workout.new
  end

  def address_attributes=(attributes)
  end

  def create
    @workout = current_user.workouts.build(params[:workout])
    if @workout.save
        flash[:success] = 'Workout Recorded'
        redirect_to root_url
    else
        render 'index'
    end
  end
end

/controllers/exercises_controller.rb内容如下:

class ExercisesController < ApplicationController
  def new
  end
end
4

1 回答 1

0

您应该在控制器操作中为新初始化的对象构建嵌套对象。试试看:

# controllers/workouts_controller.rb

class WorkoutsController < ApplicationController  
  # ...

  def index
    @workout = Workout.new
    @workout.exercises.build
  end

  # ...
end
于 2013-07-28T01:48:19.763 回答