ruby - Odd way of using nested forms (Rails) -
i'm writing (text) messaging app rails. i'm using nested_forms allow send message multiple people.
in controller, instantiate new message object, each member, build recipient object (child of message). in form, display checkbox next each recipient. want new message object has recipients have checks next them. not working.
so time form rendered, recipient objects instantiated members. in other words, default, message gets sent each member, unless specified not to. want use form allow user specify wants messages sent to
here models:
class message < activerecord::base has_many :recipients accepts_nested_attributes_for :recipients #columns: body:string, from:string, from_member_id:integer end class member < activerecord::base #columns phone:string, name:string end class recipient < activerecord::base belongs_to :message belongs_to :member #columns: member_id:integer, message_id:integer end
messages_controller.rb:
def new @message = message.new @members = member.all @members.each |member| @message.recipients << recipient.new(:member_id => member.id) end end def create @message = message.new(params[:message]) redirect_to '/somewhere' end ...
and here's form message
(app/views/message/new/html.erb)
<%= form_for(@message) |f| %> <% if @message.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@message.errors.count, "error") %> prohibited message being saved:</h2> <ul> <% @message.errors.full_messages.each |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <%= f.fields_for :recipients |builder| %> <div class="field"> <input type="checkbox" value="<%= builder.object.member_id %>" name="recipients[id]" /> /*what goes ^^^here^^^? */ <%= builder.object.member.name %> </div> <% end %> <div class="field"> <%= f.label :body %><br /> <%= f.text_field :body %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>
the commented line in form i'm having trouble. also, seems might need modify code in messagescontroller#create, i'm not sure start.
first, instead of writing checkbox html hand, should use rails helpers this. it'll save lot of work, particularly in redisplaying form upon validation failure.
to this, you'll need create attribute on recipient class:
class recipient attr_accessor :selected end
then can hook attribute checkbox:
<%= builder.check_box :selected %>
the next step make attribute something. try using :reject_if
option accepts_nested_attributes_for
. pass proc returns true if checkbox not checked, e.g.:
accepts_nested_attributes_for :recipients, :reject_if => proc { |attributes| attributes['selected'] != '1' }
see these docs details on :reject_if
:
http://api.rubyonrails.org/classes/activerecord/nestedattributes/classmethods.html
Comments
Post a Comment