我是Rails和Web Dev的新手,真的很難過。我有兩個型號user
和property
。除非您是用戶(已登錄),否則無法創建屬性。我在關聯方面遇到問題,因爲我在user
模型has_many properties
和belongs_to user
中有property
模型。當創建一個屬性時,當我檢查控制檯時,它具有正確的user_id
。Rails協會出現'無'
問題:當我在控制檯中檢查用戶時,我收到消息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
欣賞反饋。重新審視後有意義。我正在慢慢地學習,但肯定。 ;) – dgreen22