Ruby on Rails两个同时为两个不同的控制器创建动作
我有一个Threads控制器和Messages控制器。
线程has_many消息
一旦用户单击发送,我将数据发送到线程控制器以创建线程。 我想这样做
threads_controller.rb
def create ... if @thread.save #send data into messages_controller #to create the corresponding table for a message with this thread_id end
所以,基本上我试图一个接一个地做两个POSTS,如果第一个成功的话。
我认为redirect_to是我应该使用的。 是否可以使用redirect_to传递params并从另一个控制器调用create action?
编辑:我必须有一个线程(由于Ryan提到的原因而选择了错误的名称,但是为了不让人们对底部的答案感到困惑,让我们保留它)模型和消息模型在这里。 线程表只需要接收message_title。 Message表接收from_id(用户发送消息的id),to_id(用户接收消息的id)和message_content。 我试图在一个接收message_title和message_content的表单中完成所有这些操作。
我希望这有助于理解这个问题。
感谢大家
我想你会以错误的方式解决这个问题。
第一:我真的希望你不要调用模型Thread
,因为这会与Ruby类Thread
冲突。 如果是,请选择其他单词 。
现在用“请远离你的脚瞄准枪”的信息……
您不应该调用MessagesController
来为控制器创建新消息。 相反,您应该在新线程表单中使用嵌套属性:
<%= form_for @thread do |f| %> <%= f.fields_for :messages do |message| %> <%= render "messages/form", :message => message %> <% end %> <% end %>
在您的DiscussionThread
(我在这里假设它的名称)模型中,您将拥有以下这些行:
has_many :messages accepts_nested_attributes_for :messages
您可能还必须将messages_attributes
添加到此模型中的attr_accessible
属性。
这告诉DiscussionThread
模型实例也可以接受messages
关联的属性。 在ThreadsController
,操作将保持不变。
有关嵌套属性的更多信息,我建议您观看嵌套表单#1和嵌套表单#2上的Railscast。
如果我理解你的问题,你需要做的就是在Message模型上调用create方法并传入相关信息。 所以if @ thread.save就是这样的:
Message.create(:item_1 => params[:item_1])
如果您不想使用此路由,则可以使用嵌套资源,然后在向其传递正确信息时让Rails自动创建新消息。
没有理由去另一个控制器。 你可以在线程控制器中去:
@thread.messages << Message.new(...)
或者在消息控制器中执行此操作,这对我来说更有意义,因为您的用户正在创建带有线程创建的消息作为副作用。 如果正确发送thread_id
,则在params[:message][:thread_id]
,创建对象时将自动建立关联:
@message = Message.create(params[:message])
如果您需要一些其他逻辑来决定与消息关联的线程,请直接设置thread_id
:
@message.thread_id = current_thread.id # Or Thread.create(...) or whatever @message.save
我将您的基本用例视为:
- 创建新消息和线程
- 在现有线程中创建新消息
- 查看消息
- 查看线程和所有相关消息
我会建议多对多的关系: http : //api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many
# define has and belongs to many relationship class Message has_and_belongs_to_many :threads end class Thread has_and_belongs_to_many :messages end class MessageThread belongs_to :message belongs_to :thread end # use case: creating a new message and a new thread, showing message class MessagesController < ApplicationController def create @message = current_user.messages.create! :text => params[:text] @thread = @message.threads.create! end def show; @message = current_user.messages.find(params[:id); end; end # use case: creating a message in an existing thread def MessagesThreadsController < ApplicationController def create @thread = current_user.threads.find params[:id] @thread.messages.create! :text => params[:text] end end # use case: viewing all messages in a thread def ThreadsController < ApplicationController before_filter :set_thread def show @thread = current_user.threads.find params[:id] @messages = @thread.messages end end