0

私にはユーザーがいて、各ユーザーが目標を設定しています。したがって、目標はユーザーに属し、ユーザーはhas_one:目標です。ビューでform_forを使用して、ユーザーが目標を設定できるようにしようとしています。

複数形ではなく単数形のマイクロポスト(Hartlのチュートリアルから直接引用したもの)のようになると思いました。私はこの問題についてここでチュートリアルと質問を見て、さまざまなことを試しましたが、うまくいきません。

form_forが実際に機能し、正しいルートを指しているようですが、以下のエラーが発生し、それが何を意味するのかわかりません。

「LoseWeight」の未定義のメソッド`stringify_keys':String

GoalsController

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]
4

2 に答える 2

1

これを試して

# in your user model
accepts_nested_attributes_for :goal

ユーザーモデルに上記のコードを記述し、

選択タグについては、このリンクから使用してみてください

http://shiningthrough.co.uk/Select-helper-methods-in-Ruby-on-Rails
于 2012-10-04T05:20:21.450 に答える
1

エラーstringify_keysは、目標フィールドにオプションをリストした方法にあると思います.1つの引数として扱われるようにグループ化する必要があります.

accepts_nested_attributes_for :goalDipak の提案に従って使用することに加えて、ネストされたフォームが必要になります。

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、新しい目標を作成するだけでは何もしません。変数に割り当てる必要があります。

幸運を!

于 2012-10-04T16:26:05.653 に答える