Ruby on rails 我想在字段中使用:username而不是:user\u id
我是RubyonRails的初学者。我正在构建一个论坛应用程序。除了帖子和评论之外,我还希望在应用程序中使用私有消息传递系统。消息应发送给所需的用户(“只有收件人才能看到消息”)。为此,我生成了一个模型通知,将消息作为一列Ruby on rails 我想在字段中使用:username而不是:user\u id,ruby-on-rails,ruby,messaging,Ruby On Rails,Ruby,Messaging,我是RubyonRails的初学者。我正在构建一个论坛应用程序。除了帖子和评论之外,我还希望在应用程序中使用私有消息传递系统。消息应发送给所需的用户(“只有收件人才能看到消息”)。为此,我生成了一个模型通知,将消息作为一列 通知模式 class Notification < ActiveRecord::Base belongs_to :user end 类通知“create”})do | f |%> “输入您的消息”)%%> “输入收件人”)%%> 这是有效的。但是我必须在:r
通知模式
class Notification < ActiveRecord::Base
belongs_to :user
end
类通知
通知迁移
class CreateNotifications < ActiveRecord::Migration
def change
create_table :notifications do |t|
t.text :message
t.integer :recipient_id, class_name: "User"
t.timestamps null: false
t.references :user, index: true, foreign_key: true
end
end
end
class CreateNotifications
通知控制器
class NotificationsController < ApplicationController
def index
@notifications = Notification.all.order("created_at DESC")
end
def new
@notification = @notification.new
end
def create
@notification = @notification.new notification_params
if @notification.save
redirect_to(:controller => "posts", :action => "index")
else
render "new"
end
end
private
def notification_params
params.require(:notification).permit(:message, :user_id, :recipient_id)
end
end
类通知控制器“posts”,:action=>“index”)
其他的
呈现“新”
结束
结束
私有的
def通知参数
参数require(:notification).permit(:message,:user\u id,:recipient\u id)
结束
结束
通知#新建视图
<%= form_for(:notification, :url => {:action => "create"}) do |f| %>
<%= f.text_field(:message, :placeholder => "Enter your message") %>
<%= f.number_field(:recipient_id, :placeholder => "Enter the recipient") %>
<%= f.submit("send message") %>
<% end %>
{:action=>“create”})do | f |%>
“输入您的消息”)%%>
“输入收件人”)%%>
这是有效的。但是我必须在:recepient\u id字段中输入:user\u id。我想要的是我想用用户名(收件人姓名)来填充字段,而不是填充:recipient\u id。请帮助我。我感谢你的回答。提前感谢。我的建议如下-我没有测试此代码,因此,请使用此代码进行说明 将文本字段用于收件人标识,以便用户可以输入收件人姓名:
<%= f.text_field(:recipient_name, :placeholder => "Enter the recipient") %>
另外,在create
方法中,您可以查找收件人:
def create
# Look up user corresponding to the name.
u = User.find_by(name: params[:recipient_name])
# Add recipient_id to params
notification_params = notification_params.merge({recipient_id: u.id})
@notification = @notification.new notification_params
if @notification.save
redirect_to(:controller => "posts", :action => "index")
else
render "new"
end
end
你想过使用下拉列表吗?-参考:由于用户数量较多(100可能是1000),用户很难进行搜索。用户只有知道用户名才能发送消息)。你能帮我吗?在这种情况下,我认为你可以使用文本字段和收集用户名,并在你的控制器中按姓名查找收件人。你能在回答中发布吗?我不明白,因为我是rails的初学者。
def create
# Look up user corresponding to the name.
u = User.find_by(name: params[:recipient_name])
# Add recipient_id to params
notification_params = notification_params.merge({recipient_id: u.id})
@notification = @notification.new notification_params
if @notification.save
redirect_to(:controller => "posts", :action => "index")
else
render "new"
end
end