【问题标题】:Associate current_user by a controller in rails 4通过 rails 4 中的控制器关联 current_user
【发布时间】:2015-12-02 22:52:49
【问题描述】:

我正在尝试通过控制器将 current_user.id 关联到 @patient.medic_id

我在我的控制器中尝试这个:

def create
    #  @patient = Patient.new(patient_params)
    @patient = current_user.patients.build(patient_params[:medic_id => current_user.id])

    respond_to do |format|
      if @patient.save
        format.html { redirect_to @patient, notice: 'Patient was successfully created.' }
        format.json { render :show, status: :created, location: @patient }
      else
        format.html { render :new }
        format.json { render json: @patient.errors, status: :unprocessable_entity }
      end
    end
  end

这将在视图中自动使用current_user.id 填充medic_id,但是当我提交表单时,活动记录不会为患者保存其他参数,例如namelast_nameage、@ 987654329@等

这是我的模型 /medic.rb(设计 - 用户)

class Medic < ActiveRecord::Base
   has_many :patients
end

这是我的模特/patient.rb

class Patient < ActiveRecord::Base
  belongs_to :medic
end

我需要一种方法来将所有寄存器(患者)从medic-user 调用到show 视图;最好的方法是什么?

感谢您的帮助。

【问题讨论】:

  • 尝试 current_user.patients.build(patient_params.merge({:medic_id => current_user.id}))
  • 谢谢,它成功了!感谢您的帮助:)

标签: ruby-on-rails ruby devise controller associations


【解决方案1】:

在创建患者时解决问题:

medic_id = {medic_id: current_user.id}
current_user.patients.build(patient_params.merge(medic_id))

假设您在show 操作中有@medic,以获取medic-user 的所有患者:

@patients = @medic.patients

并且在您的show 视图中,您可以将@patients 作为一个数组访问。

【讨论】:

    猜你喜欢
    • 2017-09-30
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 2016-04-30
    相关资源
    最近更新 更多