【问题标题】:Rails 4 : Is there a better way to build the object: has_many through?Rails 4:有没有更好的方法来构建对象:has_many?
【发布时间】:2015-08-14 11:40:06
【问题描述】:

控制器:这是我不满意的部分。

def new
    @incident = Incident.new 
    @patient  = Patient.find(params[:patient]) 
end

# This looks like trouble waiting to happen.
def create
    @patient  = Patient.find(params[:incident][:patient])
    @incident = Incident.new(incident_params)
    @incidentcases = current_user.incidentcases.build(:incident => @incident,:patient => @patient)

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

型号:

    class Incident < ActiveRecord::Base
      has_many :incidentcases
      has_many :users,   through: :incidentcases
      has_many :patiens, through: :incidentcases
    end 
    class Incidentcase < ActiveRecord::Base
      belongs_to :user
      belongs_to :patient
      belongs_to :incident
    end

    class User < ActiveRecord::Base
      has_many :incidentcases
      has_many :incidents, through: :incidentcases
    end

    class Patient < ActiveRecord::Base
      has_many :incidentcases
      has_many :incidents, through: :incidentcases, dependent: :destroy

      accepts_nested_attributes_for :incidents, reject_if: :all_blank, allow_destroy: true
    end

它必须是在控制器中创建对象的更好方法,并让 Rails 为您处理它。

谢谢

【问题讨论】:

    标签: ruby ruby-on-rails-4 has-many-through


    【解决方案1】:

    你试过了吗:

    @patient  = Patient.find(params[:incident][:patient])
    @patient.incidents.build(incident_params)
    if @patient.save
    

    它应该自动建立连接记录。

    【讨论】:

    • 谢谢,这实际上是一种工作。我需要将 current_user 添加到其中,尽管我可以像在上面的代码中那样传递另一个关联来构建,但它抱怨:@patient.incidents.build(incident_params, :user => current_user) 参数数量错误(2 为 0..1)。唔。我会继续挖掘。
    • @lmcdougall 您有一个错误,因为build 方法采用了一个哈希参数,即attributes={},您可以合并哈希并使用user_id,而不是像这样@patient.incidents.build incident_params.merge(user_id: current_user.id)
    【解决方案2】:

    非常感谢您的帮助。每次你们帮助我时,我都会不断学习。

    对上面代码的以下更改给了我想要的东西。

    def create
        @patient  = Patient.find(params[:incident][:patient])
        @incident = Incident.new(incident_params)
        @incidentcases = current_user.incidentcases.build(:incident => @incident,:patient => @patient)
    
        respond_to do |format|
          if @incidentcases.save
    

    这包括我丢失的 user_id,它自动构建了所有连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2010-12-15
      • 2013-11-09
      • 1970-01-01
      • 2011-07-30
      • 2018-01-30
      相关资源
      最近更新 更多