【发布时间】:2017-01-24 10:20:38
【问题描述】:
我是 Rails 的初学者,无法找到解决问题的正确方法。
我有三个模型:对话、参与者、消息,它们具有以下属性:
对话:
module Messenger
class Conversation <ActiveRecord::Base
has_many :participants, :class_name => 'Messenger::Participant'
def messages
self.participants.messages.order(:created_at)
end
end
end
参与者:
module Messenger
class Participant <ActiveRecord::Base
has_many :messages, :class_name => 'Messenger::Message'
belongs_to :conversation, :class_name => 'Messenger::Conversation'
end
end
留言:
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
我的麻烦是我正在尝试制作一个表单来创建包含第一条消息的对话。表格如下所示:
= 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'
我尝试了很多方法来简化这个表单,但是我遇到了一些我不知道如何正确使用 rails 来解决的问题。
我尝试使用Field_for在我的对话表单中包含一条消息,但由于我的数据库中没有保存任何内容,但似乎我无法将消息链接到不存在的参与者。
所以基本上我希望我的第一个表单在验证后创建一个对话,将当前用户链接到该对话并将消息链接到第一个用户,但我认为有一些方法可以使用框架来做到这一点,我会不喜欢手动操作。
实现这一目标的正确方法是什么?我什至处于良好的轨道上还是应该改变一些东西或添加一些东西?
编辑:为了更容易理解,参与者得到了一个 user_id 和一个 conversation_id,这意味着这是一个关系表。我无法调整模型的属性以使其更容易,因为出于安全原因我必须保持这种方式。
【问题讨论】:
-
您可能希望通过 Conversation 中的消息关联来查看 has_many,而不是您的手动方法。
标签: ruby-on-rails ruby-on-rails-4 activerecord