【发布时间】:2014-03-31 11:20:19
【问题描述】:
我还是 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])
我相信这需要改变,但我不知道如何查询数据库以找到与用户关联的财务,因为用户只有一个。
【问题讨论】:
-
你需要更新你的路线并将
current_user.finances.find_by(..)改为current_user.finance
标签: ruby-on-rails ruby ruby-on-rails-4