0
我正在構建一個rails應用程序,供人們用來記錄他們在給定的一週內執行了多少個步驟。創建和更新來自同一字段的記錄與RoR
該應用程序的功能包括一個活動記錄器,用戶可以進入步驟,單擊日曆上顯示的一週,然後單擊提交。然後,應用程序將創建該人員ID的記錄,步驟被採取時的步驟和步驟。如果同一用戶在一天中記錄不同數量的步驟,則相同的步驟記錄器應更新步驟計數。
我無法將邏輯放入控制器,以檢查是否存在與正在添加的步驟具有相同user_id和step_date的步驟記錄。
我已經看過「find_or_initialize_by
」/「find_or_create_by
」,但沒有多少運氣。
任何人都可以指向正確的方向嗎?下面的代碼。
記錄形式(_activityLog.html.erb):
<%= simple_form_for Step.new do |f| %>
<%= f.hidden_field :user_id, :value => @user.id %>
<%= f.hidden_field :challenge_id, :value => "1" %>
<div class="input-group">
<span class="input-group-addon" id="basic-addon2">Steps I've Taken:</span>
<%= f.input :step_count, label: false, id: "step_count", class: "form-control", required: true %>
</div>
<div id="weekpicker"></div>
<%= f.input :step_date, as: :hidden, input_html: { class: 'week' } %>
<%= f.button :submit, "Log Activity", class: "submit btn-block", id: "submitWeekly" %>
<% end %>
步驟控制器(steps_controller.rb)
class StepsController < ApplicationController
before_action :set_step, only: [:show, :edit, :update, :destroy]
# GET /steps
# GET /steps.json
def index
@steps = Step.all
end
# GET /steps/1
# GET /steps/1.json
def show
redirect_to(:back)
end
# GET /steps/new
def new
@step = Step.new
end
# GET /steps/1/edit
def edit
end
# POST /steps
# POST /steps.json
def create
@step = Step.new(step_params)
respond_to do |format|
if @step.save
format.html { redirect_to @step, notice: 'Step was successfully created.' }
format.json { render :show, status: :created, location: @step }
else
format.html { render :new }
format.json { render json: @step.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /steps/1
# PATCH/PUT /steps/1.json
def update
respond_to do |format|
if @step.update(step_params)
format.html { redirect_to @step, notice: 'Step was successfully updated.' }
format.json { render :show, status: :ok, location: @step }
else
format.html { render :edit }
format.json { render json: @step.errors, status: :unprocessable_entity }
end
end
end
# DELETE /steps/1
# DELETE /steps/1.json
def destroy
@step.destroy
respond_to do |format|
format.html { redirect_to steps_url, notice: 'Step was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_step
@step = Step.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def step_params
params.require(:step).permit(:user_id, :challenge_id, :step_date, :step_count)
end
end
步驟模型(step.rb)
class Step < ActiveRecord::Base
belongs_to :user
belongs_to :challenge
end
謝謝!這很完美。爲了參考我最後的代碼: '@step = Step.where(USER_ID:step_params [:USER_ID],step_date:step_params [:step_date])。first_or_initialize(step_params)' '@ step.update(STEP_COUNT:step_params [ :step_count])' – Joe
我的榮幸!很高興這是有益的,並有一個愉快的週末! –