Ruby on rails Rails无法为新实体指定属性

Ruby on rails Rails无法为新实体指定属性,ruby-on-rails,Ruby On Rails,有人能告诉我为什么实体总是创建为name==nil: 在ProductsController中: def create @product = Product.new(name: params[:product][:name]) byebug if @product.save redirect_to users_path end end 鉴于: <%= form_for Product.new do |f| %> <%= f.label :name

有人能告诉我为什么实体总是创建为
name==nil

在ProductsController中:

def create
  @product = Product.new(name: params[:product][:name])
  byebug
  if @product.save
    redirect_to users_path
  end
end
鉴于:

<%= form_for Product.new do |f| %>
   <%= f.label :name %>
   <%= f.text_field :name %>

   <%= f.submit %>
<% end %>

型号:

class Product < ApplicationRecord
     has_many :categories
     attr_accessor :name
end
类产品
有人能告诉我为什么实体总是创建为
name==nil

因为您的
attr\u访问器
。它覆盖活动记录中自动创建的方法(知道持久性的方法)。把它拿走

(假设您的表
products
有列
name
。如果没有,请创建一个迁移来添加它。)

有人能告诉我为什么实体总是创建为
name==nil

因为您的
attr\u访问器
。它覆盖活动记录中自动创建的方法(知道持久性的方法)。把它拿走


(假设您的表
products
有列
name
。如果没有,请创建一个迁移来添加它。)

您需要确保为此使用强参数,否则参数将无法按预期传递,即

def create
  @product = Product.new(product_params)
  byebug
  if @product.save
    redirect_to users_path
  end
end

private

def product_params
  params.require(:product).permit(:name)
end

更多信息可在此处找到:

您需要确保为此使用强参数,否则参数将无法按预期传递,即

def create
  @product = Product.new(product_params)
  byebug
  if @product.save
    redirect_to users_path
  end
end

private

def product_params
  params.require(:product).permit(:name)
end

可以在此处找到更多信息:

名称
未保存在数据库中,因为您已将
名称
用作
属性访问器


产品
表中创建
名称
列。如果您已经有
name
列,则从
product.rb
模型中删除
attr\u访问器:name

名称
未保存在数据库中,因为您已将
名称
用作
属性访问器


产品
表中创建
名称
列。如果您已经有
name
列,则从
product.rb
模型中删除
attr\u访问器:name

好的,谢谢,如果rails自动创建getter和setter,那么
attr\u访问器
有什么用途呢?@nikolay:创建不受数据库中列支持的getter/setter。
attr\u访问器
是在普通ruby类中创建实例属性的setter和getter的方法。ActiveRecord模型实际上有点与众不同,因为它们是从外部输入而不是代码创建的,
attr\u accessor
的用法是什么?@nikolay:创建数据库中没有列支持的getter/setter。
attr\u accessor
是在普通ruby类中创建实例属性的setter和getter的用法。ActiveRecord模型实际上有点例外,因为它们是从外部输入创建的,而不是代码。strong参数与他遇到的问题无关。好主意,是的,但在这里完全不相关。啊,好吧,谢谢-如果删除
attr\u访问器
,没有强参数,他们不会仍然面临问题吗?不,他为什么会这样?啊,当然,明白了-对于单个属性都很好+1到您的正确答案@SergioTulentsev!强参数仅在传递源自参数的属性散列时生效
Product.new(params[:Product])
创建了一个批量分配漏洞。strong params与他遇到的问题无关。好主意,是的,但在这里完全不相关。啊,好吧,谢谢-如果删除
attr\u访问器
,没有强参数,他们不会仍然面临问题吗?不,他为什么会这样?啊,当然,明白了-对于单个属性都很好+1到您的正确答案@SergioTulentsev!强参数仅在传递源自参数的属性散列时生效<代码>产品.new(params[:Product])
创建了一个批量分配漏洞。