简体   繁体   English

将参数传递给控制器​​不起作用

[英]Passing params to controller not working

Im fairly new to RoR so I'm trying to learn by doing some projects. 我对RoR不太熟悉,所以我正在尝试通过做一些项目来学习。 The current one I'm working on is app for gym trainers with clients. 我目前正在研究的一款应用程序是面向客户的健身教练的应用程序。 When I try to create a new assessment for a client it seems as if the client_id param isn't being passed to the assessments_controller. 当我尝试为客户创建新的评估时,似乎没有将client_id参数传递给Assessments_controller。 This is the line: 这是一行:

<%= link_to 'New assessment', new_assessment_path(client_id: @client.id), class: "btn btn-xs btn-success" %> 

Error: Couldn't find Client with 'id'= 错误:找不到具有'id'=的客户端

When on the new assessment view, however, in the debug area I see this: 但是,在新的评估视图上的调试区域中,我看到以下内容:

--- !ruby/hash-with-ivars:ActionController::Parameters
elements:
  client_id: '1'
  controller: assessments
  action: new
ivars:
  :@permitted: false

When I then click 'create' the error occurs 当我单击“创建”时,发生错误

assessment_controller: 评估控制器:

 def create
   @assessment = Assessment.new(assessment_params)
   @assessment.client = Client.find(params[:client_id])
  respond_to do |format|
  if @assessment.save
    format.html { redirect_to @assessment, notice: 'Assessment was successfully created.' }
    format.json { render :show, status: :created, location: @assessment }
  else
    format.html { render :new }
    format.json { render json: @assessment.errors, status: :unprocessable_entity }
  end
end

end 结束

I am pretty sure you are assigning the new_assessment_path(client_id: @client.id) to new page and when submitting form the client id not passing to create action. 我很确定您是将new_assessment_path(client_id: @client.id)分配给新页面,并且在提交表单时客户端ID不会传递来创建操作。 There are many different solutions. 有许多不同的解决方案。

1. Solution 1.解决方案

<%= link_to 'New assessment', new_assessment_path(client_id: @client.id), class: "btn btn-xs btn-success" %>

#assestment _form.html.erb file
<%= f.hidden_field_tag 'client_id', @client_id %>

#assessments_controller:
def new
   @assessment = Assessment.new
   @client_id = params[:client_id]
end

def create
   @assessment = Assessment.new(assessment_params)
  respond_to do |format|
  if @assessment.save
    format.html { redirect_to @assessment, notice: 'Assessment was successfully created.' }
    format.json { render :show, status: :created, location: @assessment }
  else
    format.html { render :new }
    format.json { render json: @assessment.errors, status: :unprocessable_entity }
  end
end

#add :client_id
def assessment_params
   params.require(:registration).permit(..., :client_id)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM