当用户登录时,主页操作会将用户重定向到 new_status_update_path,他们将在其中看到提交新 status_update 的表单。
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'
状态更新.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
谢谢你的帮助!