带有祖先宝石的Message_controller

时间:2014-09-27 19:34:08

标签: ruby-on-rails ancestry

为新手问题道歉但是,我在我的消息控制器中引用了以下错误引用消息#new action:

ActiveRecord :: RecordNotFound(无法找到没有ID的用户):app / controllers / messages_controller.rb:18:在'new'

@recipient = User.find(params[:user_id])

我试图在我的messages_controller中加入祖先gem,特别是当我尝试回复用户收件箱中收到的邮件时(index.html.erb)。我知道目前没有ID被传递,但有没有人遇到过类似的问题?代码如下:

class MessagesController < ApplicationController

  def index
    @messages = current_user.to_messages
  end

  def outbox
    type = (params[:type] && params[:type] == "sent" ) ? "from_messages" : "to_messages"
    @messages = current_user.from_messages
  end

  def show
    @message = Message.find params[:id]
  end

  def new
    @message = Message.new(:parent_id => params[:parent_id])
    @recipient = User.find(params[:user_id])
  end

  def create
    @message = Message.new message_params
    @message.sender_id = current_user.id
    if @message.save
      flash[:success] = "Your message has been sent!"
      redirect_to users_path
    else
      flash[:failure] = "Please try again."
      redirect_to users_path
    end
  end

  def destroy
    @message = Message.find(params[:id])
    @message.destroy
    redirect_to messages_path
  end

  private

  def message_params
    params.require(:message).permit(:content, :sender_id, :recipient_id, :parent_id)
  end

end

show.html.erb(view)

From: <%= link_to @message.recipient.first_name + " " + @message.recipient.last_name, user_path(@message.recipient.id) %>,
To: <%= @message.sender.first_name + " " + @message.sender.last_name %>, 
Message: <%= @message.content %>

<% if @message.recipient_id == current_user.id %>
  <%= link_to "Reply", new_message_path(:parent_id => @message) %>
<% end %>

开始GET&#34; / messages / new?parent_id = 19&#34;在2014-09-27 15:41:18 -0400进行127.0.0.1 由MessagesController处理#new为HTML   参数:{&#34; parent_id&#34; =&gt;&#34; 19&#34;}   消息加载(0.1ms)SELECT&#34;消息&#34;。* FROM&#34;消息&#34;在哪里&#34;消息&#34;。&#34; id&#34; =?限制1 [[&#34; id&#34;,19]] 已完成404未在11毫秒内找到

ActiveRecord :: RecordNotFound(无法找到没有ID的用户):   app / controllers / messages_controller.rb:18:在'new&#39;

呈现/Users/sikendersingh/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_source.erb(0.5ms)   呈现/Users/sikendersingh/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb(1.0ms)   呈现/Users/sikendersingh/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb(1.1ms)   在救援/布局(13.8ms)内呈现/Users/sikendersingh/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb

1 个答案:

答案 0 :(得分:0)

我不确定收件人/发件人问题,但我认为您只需将user_id作为参数传递给您。所以link_to将成为:<%= link_to "Reply", new_message_path(:parent_id => @message, :user_id => @message.recipient_id) %>。这将使其在新动作中可用。