您不能只在帖子的显示表单上提供表格吗?然后将表单值传递给您的消息创建操作?
./app/controllers/message_controller.rb
class MessageController < ApplicationController
def create
@message = Message.create(create_message_params)
@message.send
end
private
def create_message_params
{}.tap do |h|
h[:from_user_id] = params[:from_user_id]
h[:to_user_id] = params[:to_user_id]
h[:text] = params[:text]
end
end
end
./app/controllers/post_controller.rb
class PostController < ApplicationController
def show
@post = Post.find(params[:id])
@message = Message.new
end
end
./app/views/posts/show.html.erb
<!-- omitting other post show html, showing just the message form -->
<% form_for(@message, url: messages_path do |f| %>
<%= hidden_field_tag(:to_user_id, @post.author.id ) %>
<%= text_area_tag(:text, @message.text) %>
<br/>
<%= f.submit("Send Message") %>
<% end %>
从 cmets 编辑 2013.08.25,希望消息在不同的视图中
首先你会在帖子的“显示”视图中有一个链接:
<%= link_to "Send a message", new_messages_path(to_user_id: @post.author.id) %>
然后您必须创建新操作和一个视图,该视图接收传入的to_user_id,并将其存储在隐藏字段中,也许。然后,当他们通过提交该消息表单向message_path 发帖时,您将拥有to_user_id、消息以及current_user.id。
这有意义吗?