Я новичок в Rails и Web Dev и очень сильно. У меня две модели: user
и property
. Вы не можете создать свойство, если вы не являетесь пользователем (вошел в систему). У меня проблемы с ассоциациями, как у меня в модели user
has_many properties
и belongs_to user
в модели property
. Когда свойство создается, когда я проверяю консоль, он имеет правильный user_id
.Rails Ассоциации, появляющиеся «nil»
Проблема: когда я проверяю пользователя на консоли, я получаю сообщение 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