我想在字段中使用 :username 而不是 :user_id

I want to use :username in the field instead of :user_id

我是 rails ruby 的初学者。我正在构建一个论坛应用程序。除了 post 和对 post 的评论之外,我还想要应用程序中的私人消息系统。该消息应发送给所需的用户 ("only recipient can see the message")。为此,我生成了一个模型 Notification,其中包含 message 作为列。

通知模型

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 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

通知#new 查看

<%= 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 %>

这是有效的。但是我必须在 :recepient_id 字段中输入 :user_id 。我想要的是我想用用户名(收件人姓名)填写字段而不是填写:recipient_id。请帮我。感谢您的回答。提前致谢。

我的建议如下 - 我没有测试过这段代码,因此,使用这段代码来说明。

使用文本字段识别收件人,以便用户可以输入收件人姓名:

<%= f.text_field(:recipient_name, :placeholder => "Enter the recipient") %>

然后在您的控制器中更新 notification_params 以允许 recipient_name 参数。

def notification_params
    params.require(:notification).permit(:message, :user_id, :recipient_name)
end

此外,在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