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

时间:2019-02-10 15:19:50

标签: ruby-on-rails

我有一个attr_accessor :members的模型分配

当我发送ajax请求时,我可以在终端上看到传递的参数,并且我的attr_accessor设置正确"members"=>["", "12", "13"]

以下是概述:

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

但是在我的模型分配中,成员访问器的值始终返回nil:

before_validation :check_members

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

为什么要为成员获取nil而不是值数组?

1 个答案:

答案 0 :(得分:-1)

似乎我需要为强参数指定一个“空数组”,以前是这样的:

class SlackNotifier
  URI = ENV['SLACK_WEBHOOK']
  CHANNEL = "#channel"
  USERNAME = "Bot"

  def self.message msg, uri: URI, channel: CHANNEL, username: USERNAME
    new(uri, channel:channel, username:username).message(msg)
  end

  def initialize uri = URI, channel: CHANNEL, username: USERNAME
    raise UriNotSetError unless uri
    @client ||= Slack::Notifier.new(uri, channel: channel , username: username)
  end

  def message msg
    @client.ping msg
  end

  class UriNotSetError < StandardError
    def message
      "The URI for the Slack Webhook was not properly configured, make sure you set ENV['SLACK_WEBHOOK']"
    end
  end

end

我把它变成了

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

现在可以使用了:)

相关来源:how to permit an array with strong parameters