views:

28

answers:

1

hi all

I have been trying to do this for ages and can seem to grasp it. hope someone can help ?

i have a 'message' model that has many through 'distribute' relationship to a 'contact_detail' model.

basically a message can have many contacts associated with it and a contact can have many messages.

I can get this to work and save it succesfully but i want also have a creater attribute on the 'distribute' model that i want to set to true for the creater of the message.

my form params are as follows :

{"message"=>{"message"=>"a great message ...", "messagable_id"=>"58", "title"=>"how are you ?", "messagable_type"=>"MachineEnquiry", "message_type_id"=>"1", "contact_detail_ids"=>["2", "2", "11", "7"]}, "commit"=>"Send message", "datetime"=>""}

The 'distributes' model has a contact_detail_id' attribute and this is all saving but before save i want to set the create attribute along with a contact_detail_id.

I can so this after save but i want to validate that the creater has been set so i have to do this before save dont i ? and not sure how to do this.

Any ideas? hopefully someone can help ?

thanks in advance rick

A: 

From the way you describe things, creator should the same for every distribution record associated with a particular message. Making much more sense to save add a new column and belongs_to relationship to Message.

class Message < ActiveRecord::Base
  belongs_to :creator, :class_name => "User" # links creator to your User model
  validates_presence_of :creator_id # ensures creator_id is not empty

  ...
end

Filling that field from the form is as simple as adding

<%= f.hidden_field :creator_id, current_user.id %>

If I'm wrong in assuming that distribution record for the same message will have the same creator, then you should look into accepts_nested_attributes_for to pass details to related models from a form.

EmFi