简体   繁体   中英

On Ruby-on-Rails it's possible to pass variables from controller to view through respond_to?

I want to submit a message and after that to show a message and open a popup window. The message is saved properly on DataBase, but the message don't show up , instead I receive this

NoMethodError in Private::Conversations#create
Showing /var/www/appror/app/views/private/conversations/_open.js.erb where line #3 raised:
undefined method `id' for nil:NilClass`

The application run on

Rails version             5.2.2;
Ruby version              2.5.3-p105 (x86_64-linux);
RubyGems version          2.7.6;
Rack version              2.0.6

after the message is save, in controller

/app/channels/private/conversation_channel.rb

class Private::ConversationsController < ApplicationController    
    def create
        recipient_id = Post.find(params[:post_id]).user.id
        conversation = Private::Conversation.new(sender_id: current_user.id, recipient_id: recipient_id)
        if conversation.save

            respond_to do |format|
                format.js {render partial: 'posts/show/contact_user/message_form/success'}
        end
....
end

from

/app/views/posts/show/contact_user/message_form/_success.js.erb

where it's

<%= render 'private/conversations/open' %>

it should show the message

/app/views/private/conversations/_open.js.erb

where

var conversation = $('body').find("[data-pconversation-id='" + 
                            "<%= @conversation.id %>" + 
                            "']");

Normally it should go forward and show the message and popup, but instead I'm receiving

NoMethodError in Private::Conversations#create
Showing /var/www/appror/app/views/private/conversations/_open.js.erb where line #3 raised:
undefined method `id' for nil:NilClass`

After debugging I saw that <%= @conversation %> is empty... so, it makes sense the error. But how I can pass @conversatio from controller to view ? It's possible to pass this using

respond_to do |format| format.js

?

Thank you!

EDIT:

thank you @max, indeed @conversation = .... solved the issue

You're missing an @ in your conversation variable in your controller, and your variable is falling out of scope. @conversation = Private::Conversation.new(sender_id: current_user.id, recipient_id: recipient_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM