ruby-on-rails - 如何从钱包模型中获取 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 = ...
变量上的成员以使电子邮件成员显示在我的表单上?有没有更好的方法来获得它?
解决方案
您可以使用label_method
和value_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..."
推荐阅读
- dymola - 找不到 dsmodel.mof 的位置 - Dymola
- virtual-machine - 在 XenServer 7.4 上运行的 VMu (Centos 6.9) 上安装“[AMD/ATI] Tonga XT GL [FirePro S7150]”显卡
- github - 通过 HTTPS 或 SSH 克隆时的带宽差异
- reactjs - Bootstrap-select 多选呈现错误
- android - 使用 Camera2 API 录制而不使用 MediaRecorder
- laravel - Vagrant 无法访问此站点
- docker - docker 缺少 var/lib/docker 文件夹
- ansible - 如何检查是否在 IF 条件内的 Jinja2 ansible 变量中定义了列表?
- python-3.x - 使用 python 执行 perl 脚本
- google-api - 如何在没有谷歌控制台的情况下获取 client_secret google api?