Rails Association:从has_many到has_one

时间:2014-03-31 00:06:08

标签: ruby-on-rails ruby ruby-on-rails-4

我还是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])

我认为这需要更改,但我现在不是如何查询数据库以查找与用户关联的资金,而用户只有一个。

2 个答案:

答案 0 :(得分:0)

您的问题与模型名称的Active Record Pluralisation有关:http://guides.rubyonrails.org/association_basics.html

试试这个:

@finance = current_user.finance

答案 1 :(得分:0)

routes.rb中,将resources :finances更改为resource :finance

然后,更改您的User型号

class User < ActiveRecord::Base
  ...

  has_one :finance
end

使用has_one关联,您可以在控制器中使用@finance = current_user.finance

现在,使用以下内容在您的视图中显示它:

<%= @finance.age %>

希望有帮助吗?