简体   繁体   English

attr_accessor 在模型中返回 nil 而在控制器中返回正确的值

[英]attr_accessor returns nil in model while returns the correct value in the controller

I have a model Assignment with attr_accessor :members我有一个带有attr_accessor :members的模型赋值attr_accessor :members

When I send my ajax request I can see in the terminal the params that are passed, and the my attr_accessor is well set "members"=>["", "12", "13"]当我发送 ajax 请求时,我可以在终端中看到传递的参数,并且我的 attr_accessor 设置得很好"members"=>["", "12", "13"]

Here is an overview:这是一个概述:

Parameters: {"utf8"=>"✓", 
 "authenticity_token"=>"YfDZ8VHrrriXLgf2RRHdZtzE8X0V5NFrEOBKZmoCw5mbvqbNKBsUVdBeJSY6HCj4YqcTQi2iiYZFhXx3SYFngw==", 
"assignment"=>{"members"=>["", "12", "13"], ....}

However in my model Assignment the value of members accessor returns always nil :但是,在我的模型分配中,成员访问器的值始终返回 nil :

before_validation :check_members

def check_members
    throw self.members # this throws: UncaughtThrowError (uncaught throw nil)
end

Why am getting nil for members instead the array of values ?为什么为成员获取 nil 而不是值数组?

It seems that I needed to specify an "empty array" for the strong parameters, What I had before is this :似乎我需要为强参数指定一个“空数组”,我以前是这样的:

params.require(:assignment).permit(:title, :members)

I turned it to我把它变成

params.require(:assignment).permit(:title, :members => [])

Now it's working :)现在它正在工作:)

A related source : how to permit an array with strong parameters相关来源: 如何允许具有强参数的数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM