在rails中形成嵌套属性视图的麻烦

时间:2013-07-28 01:11:11

标签: ruby-on-rails nested-forms nested-attributes

处理我的第一个应用程序并且有点卡住了。我正在关注嵌套属性的修改后的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

1 个答案:

答案 0 :(得分:0)

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

# controllers/workouts_controller.rb

class WorkoutsController < ApplicationController  
  # ...

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

  # ...
end