最近在学习Ruby on Rails…
开始按照书上的例子程序搭建系统.
第八章完成以后.保存了版本.然后开始兴致高昂的进入第九章.添加一个Add to Cart 按钮这一小节.
顺利的step by step 完成了界面以及后台代码的改写.
运行起服务器
当我点击页面的 Add to Cart的时候结果却不是希望的那样.
# POST /line_items # POST /line_items.json def create #@line_item = LineItem.new(params[:line_item]) @cart = current_cart product = Product.find(params[ :product_id ]) @lint_item = @cart .line_items.build( :product => product) respond_to do |format| if @line_item .save ........... |
在页面就报错了:
ActiveModel::MassAssignmentSecurity::Error in LineItemsController#create
Can’t mass-assign protected attributes: product
基于这个错误我去谷歌了一把.
看到了这样的一个网页
http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-accessible_attributes
应为根据报错的内容,我怀疑是line_item不能获取到product.接下来我修改了 line_item.rb的model
class LineItem < ActiveRecord::Base attr_accessible :cart_id , :product_id attr_accessible :product belongs_to :product belongs_to :cart end |
点击按钮还是报错了.这回不是product protected了
NoMethodError in LineItemsController#create
undefined method `save’ for nil:NilClass
再次谷歌一把.在一个英文的帖子发现了同样的问题.阅读了一下网友的回复找到了解决办法
问题还是出在@lint_item = @cart.line_items.build(:product => product)这句话
修改line_items_controller.rb文件,将@lint_item = @cart.line_items.build(:product => product)替换为
@line_item = @cart .line_items.build @line_item .product = product |
通过以上修改就能正确的运行新添加的功能.具体的原因我还在思考..如果您知道欢迎你在下面留言.
http://guides.rubyonrails.org/security.html#mass-assignment
为了安全考虑,如果允许mass-assignment的话,可以通过链接往数据库里插入数据,我也看到这一章碰到同样的问题了
所以默认不可以直接用build来new这个新对象,除非你加上
attr_accessible :product,:cart
显示告诉他们你允许mass-assignment
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?