谁能告诉我,为什么实体总是name == nil
创建:的Rails不能分配属性为新的实体
:
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
对,谢谢,如果rails自动创建getter和setter,那么attr_accessor的用法是什么? – nikolay
@nikolay:创建不受数据库中列支持的getter/setter。 –
'attr_accessor'是你在普通的ruby类中用来为实例属性创建setter和getters的东西。 ActiveRecord模型实际上有点特殊,因为它们是从外部输入而不是代码创建的。 – max