Rails Associations出现'nil'(Rails Associations appearing 'nil')
我是Rails和Web Dev的新手,真的很难过。 我有两个模型
user
和property
。 除非您是用户(已登录),否则无法创建属性。 我在user
模型has_many properties
和property
模型中的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 theuser
modelhas_many properties
andbelongs_to user
inproperty
model. When a property is created, when I check the console, it has the correctuser_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 theproperty_id
to populate for theuser
? (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
最满意答案
这是行不通的,因为我错过了打开和关闭花括号之后
(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>
相关问答
更多-
如果a$RadioBtn是无线电元素的JQuery对象,请使用: a$RadioBtn.filter(":checked"); 这将返回一个JQuery对象,表示所选的无线电输入字段。 如果您想对其执行DOM操作,请使用.get(0)方法获取DOM元素。 例: IR.Web.cRptCtl.prototype.getSelectedRadioValue = function(a$RadioBtn){ var selected = a$RadioBtn.filter(":checked"); ...
-
我在这里提出了一个你在问什么的小样本。 http://jsfiddle.net/mZhQ9/2/ 编辑:分析 var radioButtons = document.subscribeForm.myRadio; //it is crucial to store the DOM information in a variable instead of grabbing it, each single time. (DOM operations are EXTREMELY slow) var len = rad ...
-
HtmlInputRadioButton有一个属性名称Checked (返回布尔类型),你可以使用这个prop。 检查选择了哪个单选按钮。 对于示例,在RowCommand事件处理程序中获得单选按钮控件后,您必须检查prop。 喜欢这个: System.Web.UI.HtmlControls.HtmlInputRadioButton O1Radio = (System.Web.UI.HtmlControls.HtmlInputRadioButton)row.FindControl("O1"); System ...
-
我不确定你为什么要这样做,但是你会以这种方式将它保存在会话中: String selectedValue = rblYourRadioButtons.SelectedValue; Session["SelectedRadioButtonValue"] = selectedValue; 然后,在回发或每当,在gridview的Item Databound上,检查当前行Id是否与会话中存储的值匹配,如果是,则在radiobutton列表中选择该值。 我个人将值存储在数据库而不是会话中。 I'm not sur ...
-
使用SelectedItem属性检查是否选择了任何内容,使用SelectedItem属性获取所选项目的文本: If rbIsRep.SelectedIndex > - 1 Then Dim selectedItemsText = "You selected: " & rbIsRep.SelectedItem.Text End If 您可以通过编程方式更改选择,例如使用SelectedValue属性。 rbIsRep.SelectedValue = "0" 或者从aspx声明您可以使用HTML5 required属性,这是更好的选择。 您还可以使用JavaScript循环并使用从每个无线电组中检索值 $("input:radio[name=radiogroupX]:checked") You can use the HTML5 required attribute, which is better option. You can also use JavaScript loop and retrieve the value from each radio group, usi ...如果你想根据选定的值进行重定向,你可以做这样的事情...... $('#submit').click(function() { var creditcard = $('[name="credit-card"]:checked').val(); switch(creditcard) { case 'visa': // do something break; case 'mastercard': ...您应该在站点单选按钮上使用checked属性而不是selected属性。
检查所有单选列表单选按钮是否已在gridview上选中(check all radio list radio button has been selected or not on gridview)[2023-03-25]
这是行不通的,因为我错过了打开和关闭花括号之后 (var j = 0; jvar validateradios = function () { var icount = 0; var grid = document.getElementById('<%=gvQuestion.ClientID %>'); alert(grid.rows.len ... 你可以尝试内联绑定:相关文章
更多- Rails 风格指导
- rails 单元测试
- Rails常用插件
- Rails中的路由功能是如何对应的?
- rails model的一点疑惑。。。。。
- 配置sunspot tomcat结合sunspot_rails
- Rails4 已经移出了params可以解析xml的功能,拿rails4做微信API的童鞋们注意了
- 顶 使用Rails plugin weixin_rails_middleware 快速搭建微信营销平台
- rails save问题数据库表主键必须是id吗?
- Rails设置环境变量
最新问答
更多- 获取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的基本操作命令。。。