rails 4 simple_form check_boxes集合被强参数挫败

时间:2014-04-20 01:05:01

标签: ruby-on-rails ruby-on-rails-4 simple-form

我无法让我的表单上班。

模型

class User < ActiveRecord::Base
  has_many :blasts, foreign_key: "author_id"
end

class Blast < ActiveRecord::Base
  belongs_to :author, class_name: "User"
  validates :author_id, presence: true
  validates :content, presence: true, length: { maximum: 140 }
  # validates :recipients, presence: true

  [edit]
  before_validation :add_recipients

  private
  def add_recipients
    array = self.recipients
    self.recipients = ""
    array.each do |initials|
      self.recipients += "#{initials}, " unless initials.blank?
    end
    self.recipients = self.recipients[0..-3]
  end
  [end edit]
end

爆破控制器

class BlastController < ApplicationController

def new
  @blast = current_user.blasts.new
end

def create
  @blast = current_user.blasts.build(blast_params)

  if @blast.save
    flash[:success] = "Blast sent!"
    redirect_to root_url
  else
    render :new
  end

private

  def blast_params
    params.require(:blast).permit(:content, :recipients)
  end
end

视图

应用程序/视图/爆炸/ new.html.erb

 <%= render 'shared/blast_form' %> 

应用程序/视图/共享/ _blast_form.html.erb

<%= simple_form_for @blast do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <%= f.input :content, placeholder: "Compose new blast..." %>
  <%= f.input :recipients, as: :check_boxes, collection: User.all(order: 'last_name'), label_method: :full_name, value_method: :initials, include_hidden: false %>
  <%= f.submit "Send Blast", class: "btn btn-large btn-primary" %>
<% end %>

此代码允许我创建一个爆炸,但收件人是零。当我取消对收件人状态的Blast验证时,新的爆炸未被保存并产生错误:&#34;收件人不能为空。&#34;我的调试哈希表明已经提交了首字母,但是:

--- !ruby/hash:ActionController::Parameters  
utf8: "✓" 
authenticity_token: B/s22B5hrFrncxZkEUQdw2SJfpHm0qFpV2SUFg9jFR0= 
blast: !ruby/hash:ActionController::Parameters    
content: Hello world!   
recipients:
  - JC
  - AC
  - ''  
commit: Send Blast  
action: create  
controller: blasts

如果有人有任何想法,我会非常感激。这似乎应该是相当紧张的前进。提前谢谢!

1 个答案:

答案 0 :(得分:1)

尝试将accepts_nested_attributes_for :author添加到Blast模型,并像这样进行before_validation

class Blast < ActiveRecord::Base
  belongs_to :author, class_name: "User"
  accepts_nested_attributes_for :author


  before_validation :add_recipients

  private
  def add_recipients
    array = self.recipients
    self.recipients = ""
    array.each do |initials|
      self.recipients += "#{initials}, " unless initials.blank?
    end
    self.recipients = self.recipients[0..-3]
  end

end

而且,制作像这样的强参数

def blast_params
params.require(:blast).permit(:content, recipients: [])
end