我无法使用我的表格。

楷模

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验证的注释时,不会保存新的blast,并产生错误:“收件人不能为空。” 我的调试哈希显示,尽管已提交了首字母缩写:

--- !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 票数: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

  ask by BenU translate from so

未解决问题?本站智能推荐: