Arthur
Arthur

Reputation: 322

pass parameters to before_create callback in rails 3

So i am implementing a messaging system à la Facebook for a social network platform inspired by this tutorial http://www.novawave.net/public/rails_messaging_tutorial.html

I have the basic funcionality of sending messages working and now I want the user to be able to save a draft for sending it later.

when creating a message it creates copies of this message for each recipient in the before_create method of my message model.

to.each do |recipient|
    recipient = User.find(recipient)
    message_copies.build(:folder_id => recipient.inbox.id, :recipient_id => recipient.id, :read => false)
  end

I would like to pass parameters to the before_create callback so that it knows if it should build message copies to the recipients or simply save it as a draft, so I can use the same method without altering the model.

I thought of skipping callbacks for this particular case but couldn't understand how to do it.

Here is the view for creating a new message

<% form_for @message, :url => {:controller => "sent", :action => "create"} do |f| %>

<select name="message[to][]" multiple="multiple">
    <%= options_from_collection_for_select(User.find(:all), :id, :login, @message.to) %>
</select>

<p>
    Subject: <%= f.text_field :subject %>
</p>

<p>
    Body:
    <br />
    <%= f.text_area :body %>
</p>

<p>
    <%= submit_tag "Send", :name => 'do_send' %>
    <%= submit_tag "Save", :name => 'save_draft' %>
</p>

<% end %>

Any suggestions?

thanks

edit : more code!

Upvotes: 3

Views: 2130

Answers (2)

dharin
dharin

Reputation: 26

I think you can store the message and the receivers of the message with the help of Ajax in the database. That way you can continue with the message after wards similar to gmail.

Another option is to have 2 different submits for "Send" and "Save as Draft" on the form and based on commit parameter you can process the message.

Upvotes: 1

Bohdan
Bohdan

Reputation: 8408

You might have something like conditional callbacks

class Comment < ActiveRecord::Base
  before_create :send_email_to_author, :if => :author_wants_emails?,
    :unless => Proc.new { |comment| comment.post.ignore_comments? }
end

and a virtual attribute to decide either build message copies to the recipients or simply save it as a draft.

Upvotes: 1

Related Questions