首页 > 解决方案 > 如何从钱包模型中获取 simple_form 上的电子邮件成员?【复杂关系】

问题描述

我有问题。我正在尝试从 wallet_id 获取电子邮件成员,该关系不直接指向成员,而是首先指向投资者帐户,如下面的示例模型。

成员.rb

class Member < ActiveRecord::Base
  has_one :investor_account, dependent: :destroy
end

投资者账户.rb

class InvestorAccount < ActiveRecord::Base
  belongs_to :member
  has_many :wallets, dependent: :destroy
end

钱包.rb

class Wallet < ActiveRecord::Base
  belongs_to :investor_account
end

top_up.rb

belongs_to :wallet

/top_ups/_form.html.slim

= simple_form_for [:transaction, @top_up] do |f|
  .form-group
    = f.input :wallet_id, collection: @wallet, input_html: { class: 'form-control' }, include_blank: "Select..."
  .form-group
    = f.input :amount, input_html: { min: 0, value: 0 }

/controllers/top_ups_controller.rb

def new
  @top_up = TopUp.new
  @wallet = Wallet.joins(:investor_account).where(investor_accounts: {approval_status: 'approved'})
end

“f.input :wallet_id ....”上的数据已显示,但它不是会员的电子邮件,而是显示#<Wallet:0x007fd6d795e808>在所有钱包下拉列表中,以前我也编写如下代码。

= f.input :wallet_id, collection: @wallet, :id, :email, input_html: { class: 'form-control' }, include_blank: "Select..."

但是它抛出了找不到电子邮件的问题。我的问题是如何传递该@wallet = ...变量上的成员以使电子邮件成员显示在我的表单上?有没有更好的方法来获得它?

标签: ruby-on-railsrubyruby-on-rails-4activerecordruby-on-rails-5

解决方案


您可以使用label_methodvalue_method参数(文档):

= f.input :wallet_id, collection: @wallet, value_method: :id, label_method: :email, input_html: { class: 'form-control' }, include_blank: "Select..."

此外,如果您只需要 id 和电子邮件,则无需从数据库中获取所有其他数据,您可以使用pluck

# controller
def new
  @top_up = TopUp.new
  @wallet = Wallet.joins(:investor_account).where(investor_accounts: {approval_status: 'approved'}).pluck(:id, :email)
end

# form
= f.input :wallet_id, collection: @wallet, value_method: :first, label_method: :last, input_html: { class: 'form-control' }, include_blank: "Select..."

推荐阅读