2016-02-13 43 views
0

我是Rails和Web Dev的新手,真的很難過。我有兩個型號userproperty。除非您是用戶(已登錄),否則無法創建屬性。我在關聯方面遇到問題,因爲我在user模型has_many propertiesbelongs_to user中有property模型。當創建一個屬性時,當我檢查控制檯時,它具有正確的user_idRails協會出現'無'

問題:當我在控制檯中檢查用戶時,我收到消息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 

回答

0

你在做什麼是錯誤的,PROPERTY_ID不會在用戶表存儲。 你有一對多的關係。當單個用戶有3個屬性時會發生什麼,那麼您將在該單個用戶記錄中存儲3個property_id。 不,除了你在代碼中做的正確之外,Property table將具有user_id,並且你將通過在控制器中執行此操作來獲取特定用戶的所有屬性。

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

欣賞反饋。重新審視後有意義。我正在慢慢地學習,但肯定。 ;) – dgreen22