首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >RoR -带有复选框的动态下拉列表

RoR -带有复选框的动态下拉列表
EN

Stack Overflow用户
提问于 2016-04-18 21:50:53
回答 2查看 985关注 0票数 0

我希望实现一个带有复选框的动态下拉列表,这样消息的发送者可以选择多个接收者。

目前,我只在消息文本区域下有一个收件人列表。

_recipients.html.erb:

代码语言:javascript
运行
复制
<% @recipients.each do |user| %>
  <label for="user<%= user.id %>" >
    <span class="list-group-item"><%= user.full_name %></span>
    <%= check_box_tag "message[user_tokens][]", user.id, @message.users.include?(user), id: "user#(user.id)", class: "form-control" %>
  </label>

User.rb:

代码语言:javascript
运行
复制
class User < ActiveRecord::Base

  rolify
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :full_name, presence:true,
            length: {minimum: 4 }

  has_many :messages, foreign_key: :sender_id
  has_many :notes
  has_many :homeworks
  has_many :hw_comments
  belongs_to :classmodule
  belongs_to :student

recipient.rb:

代码语言:javascript
运行
复制
class Recipient < ActiveRecord::Base
    belongs_to :message
    belongs_to :user

    validates :user_id, presence: true
end

messages_controller.rb:

代码语言:javascript
运行
复制
class MessagesController < ApplicationController
    before_action :authenticate_user!

    def new
        @message = Message.new
        @recipients = User.all 
        @recipients = @recipients.page(params[:page]).per(8)
    end

    def create
        @message = current_user.messages.build(message_params)

        if @message.save
            flash[:success] = "Message sent"
            redirect_to messages_path
        else
            flash[:alert] = "Something went wrong"
            render :new
        end
    end

    def index
        @messages = Recipient.where(:user_id => current_user.id).order('created_at DESC')
    end

    private
    def message_params
        params.require(:message).permit(:title, :body, :sender_id, user_tokens: [])
    end 
end

例如,可以使用collection_select将复选框和名称放到下拉列表中吗?如果需要,我很乐意提供更多的代码。谢谢。

EN

回答 2

Stack Overflow用户

发布于 2016-04-18 22:16:37

如果您使用的是bootstrap,则可以使用下拉菜单执行此操作,请参见example http://www.bootply.com/8V6EpWyMO3

(尽管您可能会考虑在js中进行一些手动覆盖,以了解单击对所单击内容的敏感度)

对于rails部分

如果您使用的不是简单表单,而是想要引导解决方案,那么您将需要编写一个自定义输入。

票数 0
EN

Stack Overflow用户

发布于 2016-04-18 22:56:33

有很多不同的方法,比如对多个选项使用bootstrap select,这样你就只有一个select,可以选择多个选项。为此,您必须调整您的message_params

另一种方法是使用simple_formcocoon,因为cocoon处理相关模型上的新“视图”的渲染。可以是像这样简单的东西:

(为了方便起见,使用slim )

recipient_fields.slim

代码语言:javascript
运行
复制
.nested-fields
  = f.collection_select :user_id, User.all, :id, :name
  = link_to_remove_association 'remove recipient', f

并在每次要使用以下命令添加新收件人时渲染新视图:

link_to_add_association,通过cocoon处理渲染和销毁html元素。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36695963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档