I am starting to work on rails and cannot find the right way out with my problem.
I have three models: conversation, participant, messages that have the following attributes:
Conversation:
module Messenger class Conversation <ActiveRecord::Base has_many :participants, :class_name => 'Messenger::Participant' def messages self.participants.messages.order(:created_at) end end end
Participant:
module Messenger class Participant <ActiveRecord::Base has_many :messages, :class_name => 'Messenger::Message' belongs_to :conversation, :class_name => 'Messenger::Conversation' end end
Message:
module Messenger class Message <ActiveRecord::Base default_scope {order(:created_at)} default_scope {where(deleted: false)} belongs_to :participant, :class_name => 'Messenger::Participant' end end
My problem is that I am trying to create a single form for creating a conversation with the first message in it. The form is as follows:
= form_for @conversation, url: messenger.conversations_create_path do |f| .row .col-md-12.no-padding .whitebg.padding15 .form-group.user-info-block.required = f.label :title, t('trad'), class: 'control-label' = f.text_field :title, class: 'form-control' .form-group.user-info-block.required = f.label :model, t('trad'), class: 'control-label' = f.text_field :model, class: 'form-control' .form-group.user-info-block.required = f.label :model_id, t('trad'), class: 'control-label' = f.text_field :model_id, class: 'form-control' = fields_for @message, @conversation.participants.message do |m| = m.label :content, t('trad'), class: 'control-label' = m.text_area :content, class:'form-control' .user-info-block.action-buttons = f.submit t('trad'), :class => 'btn btn-primary pull-right'
I tried many ways to make this form simple, but I ran into some problems that I donβt know how to properly fix using rails.
I tried using Field_for to include a message in my conversation form, but since I didnβt save anything in my database, it seems to me that I cannot associate the message with an unused participant.
So basically, I want my first form, after validation, to create a conversation, associate the current user with this conversation, and associate a message with this first user, but I assume there are ways to do this with the framework, and I would not like do it manually.
What is the right way to achieve this? Am I even on a good track or do I need to change something or add something?
Edit: to make it more understandable, the participant received user_id and chat_id, which means it is a relationship table. I cannot adapt the attributes of my models to simplify them, since I have to keep this in line with security considerations.