Rails 协会出现 'nil'

Rails Associations appearing 'nil'

我是 Rails 和 Web Dev 的新手,真的很困惑。我有两个模型 userproperty。除非您是用户(已登录),否则您无法创建 属性。我在 user 模型 has_many propertiesproperty 模型中的 belongs_to user 中遇到了关联问题。创建 属性 后,当我检查控制台时,它具有正确的 user_id

问题:当我在控制台中检查用户时,我收到消息 property_id: nil。有人可以解释我需要什么代码才能让 property_id 填充 user 吗? (我认为这可能与 属性 之前创建的用户有关,但我认为关联会自动处理此问题)

我正在使用 devise 以防这是一个因素,并且我将 :property_id 添加到允许的参数方法中。

相关代码如下:

型号:

class Property < ActiveRecord::Base

belongs_to :user, dependent: :destroy
validates :user_id, presence: true 
mount_uploader :picture, PictureUploader
end

2)

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

has_many :properties

end

控制器:

class PropertiesController < ApplicationController

before_action :authenticate_user!, except: [:index]
before_action :set_user, only: [:show, :edit, :update]


def index
    @properties = Property.all
end

def new 
    @property = current_user.properties.new
end

def create
    @property = current_user.properties.new(property_params)
    respond_to do |format|
      if @property.save
        format.html { redirect_to @property, notice: "Property was successfully created." }
        format.json { render :show, location: @property }
      else
        format.html { render :new }
        format.json 
      end
    end
end

def update      
    respond_to do |format|
      if @property.update(property_params)
        format.html { redirect_to @property, notice: "You've successfully updated your property listing!" }
        format.json { render :show, status: :ok, location: @property }
      else
        format.html { render :edit }
        format.json { render json: @property.errors, status: :unprocessable_entity }
      end
    end
end

end

2)

class UsersController < ApplicationController

before_action :authenticate_user!
load_and_authorize_resource

def index
    @users = User.all
end

end

应用程序控制器:

class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?


protected

def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:name, :email,       :password, :password_confirmation, :property_id) }
end

你的做法是错误的,property_id 不会存储在用户 table 中。 你有一对多的关系。当单个用户拥有 3 个属性时会发生什么,那么您将在该单个用户记录中存储 3 property_id。 不,除了你在代码中做的正确之外,属性 table 将具有 user_id 并且你将通过在你的控制器中执行此操作来获得特定用户的所有属性。

@user = User.find(:user_id)
@properties = @user.properties