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

时间:2016-01-02 07:41:00

标签: ruby-on-rails ruby messaging

我是铁轨上的红宝石初学者。我正在构建一个论坛应用程序。除了帖子的帖子和评论之外,我还想要应用程序中的私人消息系统。应将消息发送给所需的用户("只有收件人才能看到消息")。为此,我生成了一个模型通知,其中包含消息

通知模型

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。请帮我。我感谢你的回答。提前谢谢。

1 个答案:

答案 0 :(得分:2)

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

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

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