【发布时间】:2012-10-04 05:03:37
【问题描述】:
我有用户,每个用户设定一个目标。因此,一个目标属于一个用户,一个用户拥有一个:目标。我试图在视图中使用 form_for 来允许用户设置他们的目标。
我认为它就像微博(直接来自 Hartl 的教程),只是单数而不是复数。我已经查看了有关此问题的教程和问题,并尝试了许多不同的方法,但我无法使其正常工作。
我得到了 form_for 实际工作并且显然指向了正确的路线,但是我收到以下错误并且我不知道这意味着什么:
“Lose Weight”的未定义方法 `stringify_keys':String
目标控制器
class GoalsController < ApplicationController
before_filter :signed_in_user
def create
@goal = current_user.build_goal(params[:goal])
if @goal.save
redirect_to @user
end
end
def destroy
@goal.destroy
end
def new
Goal.new
end
end
目标模型
class Goal < ActiveRecord::Base
attr_accessible :goal, :pounds, :distance, :lift_weight
belongs_to :user
validates :user_id, presence: true
end
用户模型
class User < ActiveRecord::Base
has_one :goal, :class_name => "Goal"
end
_goal_form(在 Users#show 上的模态)
<div class="modal hide fade in" id="goal" >
<%= form_for(@goal, :url => goal_path) do |f| %>
<div class="modal-header">
<%= render 'shared/error_messages', object: f.object %>
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>What's Your Health Goal This Month?</h3>
</div>
<div class="modal-body">
<center>I want to <%= select(:goal, ['Lose Weight'], ['Exercise More'], ['Eat Better']) %> </center>
</div>
<div class="modal-body">
<center>I will lose <%= select_tag(:pounds, options_for_select([['1', 1], ['2', 1], ['3', 1], ['4', 1], ['5', 1], ['6', 1], ['7', 1], ['8', 1], ['9', 1], ['10', 1]])) %> lbs. this month!</center>
</div>
<div class="modal-footer" align="center">
<a href="#" class="btn" data-dismiss="modal">Close</a>
<%= f.submit "Set Goal", :class => "btn btn-primary" %>
</div>
<% end %>
</div>
Routes.rb
resource :goal, only: [:create, :destroy, :new]
【问题讨论】:
-
路线中的资源不应该是资源吗?而且我不确定您是否需要在模型中设置类名“目标”
-
我不这么认为,因为它是一种单一的资源,但我绝对有可能把事情搞混了。 guides.rubyonrails.org/routing.html#singular-resources
标签: ruby-on-rails ruby-on-rails-3 form-for belongs-to has-one