Reputation: 2317
I'm unable to get my form to work.
Models
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
Blast Controller
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
Views
app/views/blasts/new.html.erb
<%= render 'shared/blast_form' %>
app/views/shared/_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 %>
This code allows me to create a blast but the recipients are nil. When I uncomment the Blast validation for recipients presence, the new blast isn't saved and produces the error: "Recipients can't be blank." My debug hash shows that initials have been submitted, though:
--- !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
I'd be super grateful if anyone has any ideas. This seems like it should be pretty strait forward. Thanks in advance!
Upvotes: 0
Views: 549
Reputation: 33542
Try adding accepts_nested_attributes_for :author
to Blast model and have a before_validation like this
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
And also,make the strong parameters as like this
def blast_params
params.require(:blast).permit(:content, recipients: [])
end
Upvotes: 1