2016-03-09 53 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