簡體   English   中英

Rails協會:從has_many到has_one

[英]Rails Associations: Going from has_many to has_one

我還是Rails的新手,我試圖找出如何將模型與用戶has_one關聯起來。

最初是假設我的用戶有很多財務狀況而設置的。 現在,我需要更改它,以便用戶擁有一項財務。

財務模式

class Finance < ActiveRecord::Base
    belongs_to :user
    validates :age, presence: true
    validates :zip, presence: true
end

用戶模型

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :finances
end

當我將has_many:finances更改為has_one:finances時,我的財務控制器拋出錯誤。

class FinancesController < ApplicationController    
  # GET /finances
  # GET /finances.json
  def index
    @finances = Finance.find_all_by_user_id current_user[:id] if current_user
  end

  # GET /finances/new
  def new
    @finance = current_user.finances.build
  end

  # GET /finances/1/edit
  def edit
  end

  # POST /finances
  # POST /finances.json
  def create
    @finance = current_user.finances.build(finance_params)

    respond_to do |format|
      if @finance.save
        format.html { redirect_to @finance, notice: 'Successfully created.' }
        format.json { render action: 'show', status: :created, location: @finance }
      else
        format.html { render action: 'new' }
        format.json { render json: @finance.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /finances/1
  # PATCH/PUT /finances/1.json
  def update
    respond_to do |format|
      if @finance.update(finance_params)
        format.html { redirect_to @finance, notice: 'Successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @finance.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /finances/1
  # DELETE /finances/1.json
  def destroy
    @finance.destroy
    respond_to do |format|
      format.html { redirect_to finances_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_finance
      @finance = Finance.find(params[:id])
    end

    def correct_user
        @finance = current_user.finances.find_by(id: params[:id])
        redirect_to root_path, notice: "Welcome to TrustRose" if @finance.nil?
    end
end

錯誤出現在這里:

 @finance = current_user.finances.find_by(id: params[:id])

我相信這將需要更改,但是由於用戶只有一個,所以我不是如何查詢數據庫來查找與該用戶關聯的財務。

您的問題與模型名稱的Active Record復寫有關: http : //guides.rubyonrails.org/association_basics.html

嘗試這個:

@finance = current_user.finance

在您的routes.rb ,將resources :finances routes.rb更改為resource :finance

然后,更改您的User模型

class User < ActiveRecord::Base
  ...

  has_one :finance
end

通過has_one關聯,可以在控制器中使用@finance = current_user.finance

現在,使用類似以下內容的視圖在您的視圖中顯示它:

<%= @finance.age %>

希望有幫助嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM