2016-03-09 52 views
0

我有一个表格,其取入数据的负载这里的形式为一个例子:导轨形式输出一个得分

<%= form_for(@profile) do |f| %> 
    <% if @profile.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@profile.errors.count, "error") %> prohibited this profile from being saved:</h2> 
     <ul> 
     <% @profile.errors.full_messages.each do |message| %> 
     <li><%= message %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

<form> 

<div class="form-group"> 
    <label for="Email">Small bio about yourself</label> 
    <%= f.text_area :bio, :class => "form-control", :id => "Email", :rows => "3", 
     :placeholder => "bio here"%> 
    </div> 

<div class="field"> 
    <%= f.fields_for :portfolios do |portfolio| %> 
     <%= render partial: 'partials/portfolio_fields', :f => portfolio %> 
    <% end %> 
    <div class="links"> 
     <%= link_to_add_association 'add image', f, :portfolios %> 
    </div> 
    </div> 

</form> 
<% end %> 

轮廓(脚手架)属于由色器件创建的用户。例如,如果用户填写自己的生物,他会得到一个分数(+2分),对于他添加的每个投资组合,他会得到更多(+5分),并且在形式结束时得分是计算。

像这样

if bio.empty? 
score = 3 
else 
score = 0 
end 
+1

什么是你的问题? – toddmetheny

回答

1

如果你想为他在信息填写显示比分的用户(例如:生物,组合)等,那么你需要看在客户端实现使用javascript。

但是如果你想在表单提交,将其保存到profiles表,并在以后显示这些信息给用户,那么你可以通过对Profile模型回调如下实现它:

class Profile < ActiveRecord::Base 
    belongs_to :user 

    before_save :assign_score 

    protected 
    def assign_score 
    score = self.score || 0 
    score += 3 if self.changes.include?(:bio) and self.bio.present? 
    score += 5 if self.portfolios.present? 

    self.score = score 
    end 
end 

问题使用这种方法,就是每次更新profile创纪录的时间,你需要确保你不会增加一倍存储其他信息一样bio_calculated等,否则,您不断添加比分为bioportfolios

计算

或者,如果你想只显示分数,这是动态计算的,你可以在你的Profile型号如下定义自定义的方法:

class Profile < ActiveRecord::Base 
    belongs_to :user 

    def score 
    score = 0 
    score += 3 if self.bio.present? 
    score += 5 * self.portfolios.count 
    score # this last line is optional, as ruby automatically returns the last evaluated value, but just added for explicity 
    end 
end 
+0

我忘记添加到上面的源代码中的是“分数”是分数需要保存的列。我试过self.score,但它不起作用? –

+0

我怎么能将这个存储在称为分数的配置文件表中的列中? –

+0

当你尝试使用'before_save:assign_score'的第一种方法时,你是否收到错误?如果不尝试在'assign_score'方法中添加'puts'语句或调试器并遍历这些步骤。 – Dharam