【问题标题】:Rails rendering vs re_direct with formsRails 渲染与带有表单的 re_direct
【发布时间】:2013-08-25 01:45:32
【问题描述】:

我有一个测试应用程序,它允许用户创建帖子,然后其他用户可以对这些帖子发表评论。我现在正在尝试为用户创建一种从帖子中向另一个用户发送消息的方式,但是我遇到了表单问题。当用户 B 想要在用户 A 的帖子中 PM 用户 A 时,我希望消息的表单具有预填充数据。即。

收件人:@user.username 来自:@current_user.username

由于消息是它们自己的模型和控制器,我似乎无法重定向用户并仍然保留该用户的特定信息。

【问题讨论】:

标签: ruby-on-rails model-view-controller


【解决方案1】:

您不能只在帖子的显示表单上提供表格吗?然后将表单值传递给您的消息创建操作?

./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。

这有意义吗?

【讨论】:

  • 考虑得很周到。但是我真的希望它是一个单独的页面,而不是在帖子页面上。
  • 这是一个微不足道的变化,正如我现在在答案底部的编辑中提到的那样。有意义吗?
  • 老兄,太棒了!信不信由你,我之前尝试过 link_to 方法,但它不起作用,现在我明白了原因。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多