當用戶登錄時,home action將用戶重定向到new_status_update_path,他們將在其中看到表單提交新的status_update。未定義方法`> ='爲零:NilClass - 無法弄清楚這意味着什麼
def home
if user_signed_in?
redirect_to new_status_update_path
end
end
然後status_update_controller內的新的動作應該簡單地在status_update對象傳遞到視圖的形式,使得它可以被操縱。
狀態更新控制器:
def new
@status_update = current_user.status_update.build if user_signed_in?
end
查看:
<div class="row">
<div class="span6 offset3">
<%= form_for(@status_update) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :weight %>
<%= f.text_field :weight %>
<%= f.label :bf_pct %>
<%= f.text_field :bf_pct %>
<%= f.submit "Post", class:"btn btn-large btn-primary" %>
<% end %>
渲染錯誤:
NoMethodError in StatusUpdatesController#new
undefined method `>=' for nil:NilClass
app/models/status_update.rb:36:in `default_values'
app/controllers/status_updates_controller.rb:10:in `new'
status_update.rb
class StatusUpdate < ActiveRecord::Base
belongs_to :user
after_initialize :default_values
attr_accessible :current_weight,
:current_bf_pct,
:current_lbm,
:current_fat_weight,
:change_in_weight,
:change_in_bf_pct,
:change_in_lbm,
:change_in_fat_weight,
:total_weight_change,
:total_bf_pct_change,
:total_lbm_change,
:total_fat_change,
:previous_weight,
:previous_bf_pct,
:previous_lbm,
:previous_fat_weight,
:created_at
validates :user_id, presence: true
validates :current_bf_pct, presence: true,
numericality: true,
length: { minimum: 2, maximum:5 }
validates :current_weight, presence: true,
numericality: true,
length: { minimum: 2, maximum:5 }
validates :current_lbm, presence: true
validates :current_fat_weight, presence: true
def default_values
if self.current_bf_pct >= 0.5
self.current_bf_pct /= 100
if self.current_bf_pct <= 0.04
self.current_fb_pct *= 100
end
end
self.current_fat_weight = self.current_weight * self.current_bf_pct
self.current_lbm = self.current_weight - self.current_fat_weight
end
def previous_status_update
previous_status_update = user.status_update.where("created_at < ? ", self.created_at).first
if previous_status_update == nil
return self
else
previous_status_update
end
end
default_scope order: 'status_updates.created_at DESC'
end
感謝您的幫助!
你可以顯示你的'status_update.rb'文件的樣子嗎?特別是線36周圍的區域? – Zajn
你的異常告訴你它被引發('app/models/status_update.rb:36:在'default_values'中)。但你不提供這種方法 –
當然可以!我在底部添加了它。 –