我正在构建一个包含两个模型的 Rails 应用程序,两个模型都有另外两个嵌套模型:
联系人 -> 跟踪器 -> 电子邮件
和
目标 -> 阶段 -> 模板
我想在特定跟踪器的显示页面上显示来自特定目标的信息,但我正在努力让正确的数据出现。
我的 Tracker 参数中有一个 goal_id 字段,我已将此行添加到我的 Tracker 控制器,但我认为我做错了:
@goals = Goal.find(params[:id])
我确定这将是一个非常明显的错误,但我对 Rails 如此陌生,以至于我似乎无法正确处理它,我很乐意收到您的任何建议。提前致谢!
追踪器型号:
class Tracker < ApplicationRecord
belongs_to :contact
has_one :goal
has_many :emails, dependent: :destroy
end
目标模型:
class Goal < ApplicationRecord
has_many :stages , dependent: :destroy
has_many :trackers
end
追踪器控制器:
class TrackersController < ApplicationController
before_action :get_contact
before_action :set_tracker, only: %i[ show edit update destroy ]
# GET /trackers or /trackers.json
def index
@trackers = @contact.trackers
end
# GET /trackers/1 or /trackers/1.json
def show
@goals = Goal.find(params[:id])
end
# GET /trackers/new
def new
@tracker = @contact.trackers.build
end
# GET /trackers/1/edit
def edit
end
# POST /trackers or /trackers.json
def create
@tracker = @contact.trackers.build(tracker_params)
respond_to do |format|
if @tracker.save
format.html { redirect_to contact_trackers_path(@contact), notice: "Tracker was successfully created." }
format.json { render :show, status: :created, location: @tracker }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @tracker.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /trackers/1 or /trackers/1.json
def update
respond_to do |format|
if @tracker.update(tracker_params)
format.html { redirect_to contact_tracker_path(@contact), notice: "Tracker was successfully updated." }
format.json { render :show, status: :ok, location: @tracker }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @tracker.errors, status: :unprocessable_entity }
end
end
end
# DELETE /trackers/1 or /trackers/1.json
def destroy
@tracker.destroy
respond_to do |format|
format.html { redirect_to contact_trackers_path(@contact), notice: "Tracker was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def get_contact
@contact = Contact.find(params[:contact_id])
end
def set_tracker
@tracker = @contact.trackers.find(params[:id])
end
# Only allow a list of trusted parameters through.
def tracker_params
params.require(:tracker).permit(:name, :contact_id, :goal_id, :stage_id, :status, :note)
end
end
显示跟踪器的页面视图:
<div class="card">
<h3>Goal</h3>
<%= @goals.name %>
</div>