首页 \ 问答 \ Rails Associations出现'nil'(Rails Associations appearing 'nil')

Rails Associations出现'nil'(Rails Associations appearing 'nil')

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

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

我正在使用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

I'm new to Rails and Web Dev and really stumped. I have two models user andproperty. You cannot create a property unless you are a user (logged in). I'm having problems with associations as I have in the user model has_many properties and belongs_to user in property model. When a property is created, when I check the console, it has the correct user_id.

Problem: When I check the user in the console, I get message property_id: nil. Can someone explain what code I need in order for the property_id to populate for the user? (I figure it probably has something to do with the user being created before the property but I thought the associations would automatically take care of this)

I'm using devise in case that is a factor and I added :property_id to the permitted parameters method.

Relevant code is below:

Models:

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

Controllers:

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

Application Controller:

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

原文:https://stackoverflow.com/questions/35375533
更新时间:2022-02-15 09:02

最满意答案

这是行不通的,因为我错过了打开和关闭花括号之后

(var j = 0; j <inputs.length; j ++){

<script type="text/javascript">
    var validateradios = function () {
        var icount = 0;
        var grid = document.getElementById('<%=gvQuestion.ClientID %>');
        alert(grid.rows.length);
        for (var i = 1; i < grid.rows.length; i++) {
            var row = grid.rows[i];
            var targetcell = row.cells[2];
            var inputs = targetcell.getElementsByTagName("input");
            for (var j = 0; j < inputs.length; j++) {
                if (inputs[j].checked) {
                    icount++; break;  
                }
            }
        }
        alert(icount)
        if (icount == (grid.rows.length - 1))
            alert(' all rows checked');
        else
            alert('some rows need to be checked');
    }
</script>

This is not working because i have missed opening and closing curly bracket after for

(var j = 0; j < inputs.length; j++) {

<script type="text/javascript">
    var validateradios = function () {
        var icount = 0;
        var grid = document.getElementById('<%=gvQuestion.ClientID %>');
        alert(grid.rows.length);
        for (var i = 1; i < grid.rows.length; i++) {
            var row = grid.rows[i];
            var targetcell = row.cells[2];
            var inputs = targetcell.getElementsByTagName("input");
            for (var j = 0; j < inputs.length; j++) {
                if (inputs[j].checked) {
                    icount++; break;  
                }
            }
        }
        alert(icount)
        if (icount == (grid.rows.length - 1))
            alert(' all rows checked');
        else
            alert('some rows need to be checked');
    }
</script>

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。