Rails Associations出现'nil'

时间:2016-02-13 02:53:36

标签: ruby-on-rails-4 associations

我是Rails和Web Dev的新手,真的很难过。我有两个模型userproperty。除非您是用户(已登录),否则无法创建属性。我在user模型中的has_many properties模型belongs_to userproperty中遇到了关联问题。创建属性时,当我检查控制台时,它具有正确的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

1 个答案:

答案 0 :(得分:0)

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

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