2015-01-13 2 views
0

RoR에 익숙하지 않아 일부 구문을 실험하는 데 어려움이 있습니다.Ruby On Rails를 사용하여 숫자 추가 및 데이터베이스 저장

여기에서 나오는 두 개의 입력 된 번호를 추가하는 방법을 알고하지 않습니다

<div class="field"> 
<%= f.label :point1 %><br> 
<%= f.number_field :point1 %> 

</div> 
<div class="field"> 
<%= f.label :point2 %><br> 
<%= f.number_field :point2 %> 

</div> 

나는 또한 그들의 합계를 포함하여 데이터베이스에 번호를 저장합니다. 인터넷에서 이미 검색했지만 결과에 만족하지 않습니다.

누군가가 도와 주길 바랍니다. 고맙습니다. 덧붙여서, 합계 이외의 2 개의 입력 수치를 데이터베이스에 저장하는 방법은 알고 있습니다.

이들은 나의 코드입니다!

player.rb

class Player < ActiveRecord::Base 
    before_save :add_point1_and_point2 
private 
def add_point1_and_point2 
    self.point3 = self.point1 + self.point2 
    self.save 
end 
end 

_form.html.erb

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

     <ul> 
     <% @player.errors.full_messages.each do |message| %> 
     <li><%= message %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

<% sum = 0 %> 
    <div class="field"> 
    <%= f.label :point1 %><br> 
    <%= f.number_field :point1 %> 

    </div> 
    <div class="field"> 
    <%= f.label :point2 %><br> 
    <%= f.number_field :point2 %> 

    </div> 


    </div> 
    <div class="actions"> 
    <%= f.submit %> 

    </div> 
<% end %> 

players_controller.rb

class PlayersController < ApplicationController 

    before_action :set_player, only: [:show, :edit, :update, :destroy] 

    # GET /players 
    # GET /players.json 
    def index 
    @players = Player.all 
    end 

    # GET /players/1 
    # GET /players/1.json 
    def show 
    end 

    # GET /players/new 
    def new 
    @player = Player.new 
    end 




    # GET /players/1/edit 
    def edit 
    end 

    # POST /players 
    # POST /players.json 
    def create 

    # @player = Player.new(sum_num :point3) 

    @player = Player.new(player_params) 

    respond_to do |format| 
     if @player.save 

     format.html { redirect_to @player, notice: 'Player was successfully created.' } 
     format.json { render :show, status: :created, location: @player } 
     else 
     format.html { render :new } 
     format.json { render json: @player.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /players/1 
    # PATCH/PUT /players/1.json 
    def update 
    respond_to do |format| 
     if @player.update(player_params) 
     format.html { redirect_to @player, notice: 'Player was successfully updated.' } 
     format.json { render :show, status: :ok, location: @player } 
     else 
     format.html { render :edit } 
     format.json { render json: @player.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /players/1 
    # DELETE /players/1.json 
    def destroy 
    @player.destroy 
    respond_to do |format| 
     format.html { redirect_to players_url, notice: 'Player was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 



    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_player 
     @player = Player.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def player_params 
     params.require(:player).permit(:point1, :point2) 
    end 

end 

답변

2

확인 ActiveRecord Callbacks. 당신의 model에서 before_saveafter_save

를 찾아, 당신은 잘 가지 방법 중 몇 그렇게가이

before_save :add_point1_and_point2 
private 
def add_point1_and_point2 
    sum_value = self.point1 + self.point2 
    self.assign_attributes(sum_column: sum_value) 
end 
+0

스택 레벨이 너무 깊음 – ana

+0

아나, 질문 자체에 모든 코드를 추가해야합니다. 당신은 질문, 지역 사회 대답을 부탁드립니다! :) – gkolan

+0

ahhh : D 나는 너무 어리 석다. 하하! – ana

2

유사한 코드가 있어야합니다. 그러나 self.savebefore_save 또는 after_save에 사용할 수 없습니다. save는 이러한 before_save 및 after_save를 다시 호출하므로 스택 수준이 너무 깊습니다. 대신 어떤 콜백을 트리거하지 않습니다 update_column를 사용

after_save :add_point1_and_point2 
def add_point1_and_point2 
    update_column(:point3, point1 + point2) 
end 
+0

또 다른 오류가 나타나 가 "update_column (POINT3, POINT1 + POINT2)" – ana

+0

액티브 :: ActiveRecordError PlayersController에 #이 'after_save'에 – ana

+0

변경 'before_save'을 만드는 "새 레코드 객체에 업데이트 할 수 없습니다" – Abk

2

1 일 : 당신이 당신의 결과 열을 누락하는 열 '합'을 할 수있다

#이이 선수에 새 열 합계를 추가합니다.

rails g migration add_sum_to_players sum:integer 
rake db:migrate 

다음 모델 파일이 시도 :

#player.rb 
class Player < ActiveRecord::Base 

before_save :calculate_sum 

private 
    def calculate_sum 
    result = point1 + point2 
    self.assign_attributes(sum: result) 
    end 
end 

우리가 (POINT1과 POINT2의 + 등의 합) 속성을 할당하는, 그래서 이것은 저장하지 않을 것처럼. 이것은 before_save를 트리거하는 것처럼 할당하는 것입니다. 그래서 저장이 시작될 때이 합계 값이 자동으로 저장됩니다. :)

+0

이것을 수락하는 것을 고려하십시오 문제가 해결 된 경우 전체 코드는 여기에서 확인할 수 있습니다. https://gist.github.com/AjayROR/b051edaf31d4f827d71e – Ajay