[英]has_one, belongs_to What am I doing wrong?
我有用戶和每個用戶設置目標。 因此,目標屬於用戶和用戶has_one:目標。 我試圖在視圖中使用form_for以允許用戶設置他們的目標。
我認為它就像微博(這是直接來自Hartl的教程),只是用單數而不是復數。 我已經在這里查看了關於這個問題的教程和問題,並嘗試了許多不同的東西,但我無法讓它工作。
我得到了form_for實際工作,顯然指向正確的路線,但我得到以下錯誤,我不知道這意味着什么:
未定義方法`stringify_keys'表示“減肥”:字符串
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(這是用戶#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]
嘗試這個
# in your user model
accepts_nested_attributes_for :goal
在您的用戶模型中寫上面的代碼,和
對於select標簽,請嘗試使用此鏈接
http://shiningthrough.co.uk/Select-helper-methods-in-Ruby-on-Rails
我希望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
,你的“新”動作應該是@goal = Goal.new
,只是創建一個新的目標什么都不做,你需要將它分配給一個變量,讓它進入頁面。
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.