简体   繁体   中英

Form_for error in Ruby on Rails

I keep running into an issue while attempting to send messages from one user to another.

User Model

has_many :sent_messages, class_name: "Message" , foreign_key: :sender_id
has_many :received_messages, class_name: "Message", foreign_key: :receiver_id

def friendships
 Friendship.where("sender_id = ? or receiver_id = ? and status = ?", self.id, self.id, "accepted")
end

def friends
 ids = friendships.pluck(:sender_id, :receiver_id).flatten.uniq
 ids.delete(self.id)

 friends = User.where(id: ids)
end

User show view

<% current_user.friends.map do |f| %>
    <strong><%= link_to "#{f.name}", conversation_path(f.id) %></strong><p></p>
<% end %>

Conversations show view

<% @test.map do |c| %>
<%= c.sender.name %>:
<%= c.message %><p></p>
<% end %>

<%= form_for Message.new do |f| %>
<%= f.text_field :message %>
<%= f.submit %>
<% end %>

Conversations controller

class ConversationsController < ApplicationController

def show
 #current user
 #other use in conversation
 @other_user = User.find(params[:id])
 @test = Message.where("sender_id IN (#{current_user.id},#{@other_user.id}) AND receiver_id IN (#{current_user.id}, #{@other_user.id})")
end

end

Messages create controller

class MessagesController < ApplicationController

  def index
   @message = current_user.friends
  end


  def create
    @message = Message.new(params[:message].permit!)
    @message.sender_id = current_user.id
    @message.receiver_id = User.find(params[:id])
  if @message.save
    redirect_to :root 
  end
end
end

When I use the form_for in conversations show view, I get the "Couldn't find User without an ID" error, although I feel like it should be feeding it the IDs for both users?

The problem is in this line:

@message.receiver_id = User.find(params[:id])

params[:id] is nil . You must send the id in the form:

<%= form_for Message.new do |f| %>
<%= f.text_field :message %>
<%= f.hidden_field :id, :value => the_user_id_goes_here %>
<%= f.submit %>
<% end %>

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