我正在尝试在Rails应用程序中设置一个消息传递系统,使接收者可以在单独的页面上查看其消息。到目前为止,我已经能够进行所有设置,以便消息可以成功发送,但是问题是它不会将自身分配给消息接收者,标记为“ receiver_id”。由于我目前已经实现了一个“关系”模型来跟踪关注者/关注者,因此我尝试使用该模型作为分配用户的一种方式,但尚未成功。请在下面查看我的代码:
消息控制器
class MessagesController < ApplicationController
#before_action :set_receiver, only: [:new, :create]
def create
@message = current_user.messages.build(message_params)
#@message.receiver_id = @receiver.id
if @message.save!
flash[:success] = "message sent!"
redirect_to root_url
else
render 'new'
end
end
def new
@message = current_user.messages_received.new
#@receiver_id = :followed_id
end
def view
end
def destroy
end
def index
@message = current.user.messages
end
def show
@message = Message.find(params[:id])
end
private
def message_params
params.require(:message).permit(:content, :receiver_id, :sender_id).merge(sender_id: current_user.id) #.merge(receiver_id: followed_id.id)
end
Message.rb
class Message < ApplicationRecord
#belongs_to :user, optional: true, :foreign_key=> 'user_id'
belongs_to :sender, :class_name=>'User', :foreign_key=>'sender_id'
belongs_to :receiver, :class_name=>'User', optional: true, :foreign_key=>'receiver_id'
scope :unread, -> { where read: false}
validates :user_id, presence: true
validates :content, presence: true
end
User.rb
class User < ApplicationRecord
has_many :messages_sent, class_name: "Message", foreign_key: :sender_id
has_many :messages_received, class_name: "Message", foreign_key: :receiver_id
has_many :messages
new.html.erb
<% provide(:title, "Send Message") %>
<h1> Send Message </h1>
<div class="row">
<div class= "col-md-6 col-md-offset-3">
<%= form_for(@message) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "message", object: f.object %>
</div>
<%= f.submit "Submit", class: "btn btn-primary" %>
routes.rb
Rails.application.routes.draw do
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
root 'static_pages#home'
get '/help', to: 'static_pages#help'
get '/privacy', to: 'static_pages#privacy'
get '/contact', to: 'static_pages#contact'
get '/signup', to: 'users#new'
get '/login', to: 'sessions#new'
get '/message', to: 'messages#new'
post '/message?id=USER_ID', to: 'messages#create'
get '/view_message', to: 'messages#view'
get 'auth/:provider/callback' => 'sessions#callback'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
resources :users do
member do
get :following, :followers, :messages
end
end
resources :user do
get :profile
resource :messages, only: [:new, :create]
end
resources :message, only: [:new, :create, :show]
<% end %>
_follow_form.html.erb
<% unless current_user?(@user) %>
<div id= "follow_form">
<% if current_user.following?(@user) %>
<%= render 'unfollow' %>
<%= link_to "Send Message", message_path(@user), class: "btn btn-lg btn-primary" %>
<%= hidden_field_tag :followed_id, @user.id %>
<% else %>
<%= render 'follow' %>
<% end %>
</div>
<% end %>