Ruby on Rails:使用其他模型的数据显示下拉菜单

时间:2017-01-09 16:47:45

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 drop-down-menu

我有一个Ruby on Rails系统,我有这些表:用户,UserAccounts,帐户和带有模式的电子邮件:

User (id, firstname, surname, password)
UserAccount (user_id, account_id)
Account (id, emailaddress, port, domain)
Email (id, account_id, subject, message)

我要做的是在创建新电子邮件时,我想要所有用户的帐户' emailaddress变量显示在下拉菜单中的视图上,当用户点击保存时,我希望将account_id保存在电子邮件表格中。

我可以在account_id的下拉菜单中使用以下代码行显示views/emails/_form.html.erb

<%= f.collection_select :account_id, Useraccount.where(user_id: session[:user_id]), :account_id, :account_id %>

但我无法更改此内容以显示电子邮件地址,我已尝试使用以下代码:

<%= f.collection_select :account_id, Useraccount.where(user_id: session[:user_id]), :account_id, :Account.where(id: account_id).email %>

但是这给了我错误undefined local variable or method account_id&#39;对于#&lt;#:0x72cde60&gt;`

有人可以帮忙吗?

表单的完整代码是:

<%= form_for @email do |f| %>

  <% if @email.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@email.errors.count, "error") %> prohibited this email from being saved:
      </h2>
      <ul>
        <% @email.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
 <%= f.collection_select :account_id, Useraccount.where(user_id: session[:user_id]), :account_id, :Account.where(id: account_id).email %>
  <p>
    <%= f.label :subject %><br>
    <%= f.text_field :subject %>
  </p>

  <p>
    <%= f.label :message %><br>
    <%= f.text_area :message %>
  </p>

  <p>
    <%= f.submit %>
  </p>

2 个答案:

答案 0 :(得分:0)

您还没有发布足够的代码来帮助您。至少需要查看您将collection_select放在哪个表单上...假设它是您要发送的新电子邮件的表单?

顺便说一句,拥有复数的Active Record类名是非常罕见的。 Breaking Rails命名约定是让自己陷入混乱局面的好方法。

答案 1 :(得分:0)

使用select代替collection_select更容易。我还假设您在用户模型中有has_many through关联。

f.select :account_id, User.find(session[:user_id]).accounts.map{ |a| [a.emailaddress, a.id] }

collection_select将方法名称作为参数,它只适用于您的情况。

相关问题