【问题标题】:has_one, belongs_to What am I doing wrong?has_one,belongs_to 我做错了什么?
【发布时间】: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]

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3 form-for belongs-to has-one


【解决方案1】:

我预计 stringify_keys 错误取决于您在目标字段中列出选项的方式,它们需要被分组以被视为一个参数。

除了按照 Dipak 的建议使用 accepts_nested_attributes_for :goal 外,您还需要一个嵌套表单。

form_for @user do |form|
  fields_for @goal do |fields|
    fields.select :goal, ['Lose Weight', 'Exercise More', 'Eat Better']

保存操作现在是在用户的上下文中,因此通过的属性将包括目标字段的一部分:

user =>{goal_attributes => {:goal => 'Eat Better'}}

您可以通过更新用户来保存这些属性:

@user.update_attributes(params[:user])

顺便说一句,你的“新”动作应该是@goal = Goal.new,只是创建一个新目标没有任何作用,你需要将它分配给一个变量,让它进入页面。

祝你好运!

【讨论】:

    【解决方案2】:

    试试这个

    # in your user model
    accepts_nested_attributes_for :goal
    

    在您的用户模型中编写上述代码,然后

    对于选择标签,请尝试从此链接中使用

    http://shiningthrough.co.uk/Select-helper-methods-in-Ruby-on-Rails
    

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 2021-04-19
      • 2017-03-13
      • 2017-01-18
      • 2013-06-24
      相关资源
      最近更新 更多