我正在构建一个rails应用程序,人们将使用它来记录他们在给定的一周内执行的步数。
应用程序的功能包括一个人可以输入步骤的活动记录器,单击日历上显示的一周,然后单击“提交”。然后,应用程序将创建人员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
答案 0 :(得分:1)
也许是这样的?
def create
# ... leaving some stuff out :)
@step = Step.where(user_id: params[:user_id], step_date: params[:step_date]).first_or_initialize(step_params) # or first_or_create
# ... other code here (leaving more stuff out)
end