繁体   English   中英

Rails simple_form关联问题

[英]Rails simple_form association issue

我很难让:association helper工作。 基本上,我希望有一个包含所有32个团队的选择框,而不是无用的:team_id号,我想使用ActiveRecord魔术来显示相应团队的'abbr'或'city'。 我正在使用MySQL DB btw。

楷模

class Player < ActiveRecord::Base
    belongs_to :teams
end

class Team < ActiveRecord::Base
    has_many :players
end

调节器

@player = Player.find(params[:id])

视图

<%= simple_form_for @player do |f| %>
    <%= f.input :first %>
    <%= f.input :last %>
    <%= f.association :teams %>
    <%= f.button :submit %>
<% end %>

==================

只是为了帮助在此处可视化数据,是对数据库中显示的数据进行采样。

数据库-团队

+----+-----------+-----------+---------------------+---------------------+------+
| id |   city    |   name    |     created_at      |     updated_at      | abbr |
+----+-----------+-----------+---------------------+---------------------+------+
|  1 | Arizona   | Cardinals | 2013-08-27 17:23:55 | 2013-08-27 17:23:55 | ARI  |
|  2 | Atlanta   | Falcons   | 2013-08-27 17:23:55 | 2013-08-27 17:23:55 | ATL  |
|  3 | Baltimore | Ravens    | 2013-08-27 17:23:55 | 2013-08-27 17:23:55 | BAL  |
|  4 | Buffalo   | Bills     | 2013-08-27 17:23:55 | 2013-08-27 17:23:55 | BUF  |
+----+-----------+-----------+---------------------+---------------------+------+

数据库-玩家

+----+---------+----------+--------+-----------------+---------------------+---------------------+
| id | team_id | position | first  |      last       |     created_at      |     updated_at      |
+----+---------+----------+--------+-----------------+---------------------+---------------------+
|  1 |       5 | QB       | Derek  | Anderson        | 2013-08-26 18:48:59 | 2013-08-27 20:41:37 |
|  2 |      24 | QB       | Matt   | Barkley         | 2013-08-26 18:48:59 | 2013-08-26 18:48:59 |
|  3 |      18 | QB       | McLeod | Bethel-Thompson | 2013-08-26 18:48:59 | 2013-08-26 18:48:59 |
|  4 |       6 | QB       | Matt   | Blanchard       | 2013-08-26 18:48:59 | 2013-08-26 18:48:59 |
|  5 |      26 | QB       | Sam    | Bradford        | 2013-08-26 18:48:59 | 2013-08-26 18:48:59 |
+----+---------+----------+--------+-----------------+---------------------+---------------------+

首先,您应该对belongs_to使用单数形式,而不是复数形式。 所以你的模型变成

class Player < ActiveRecord::Base
  belongs_to :team
end

...并且您的表单输入也以单数形式表示,其中abbr是select中的显示字段, id是传递给参数的实际值:

<%= f.association :team, :label_method => :abbr, :value_method => :id

传递label_method。

喜欢

<%= f.association :team, label_method: "#{:city} #{:name}" %>

更好的是,您可能已经具有full_name功能,只需调用

如果simple_form无法正确猜测通过关联的形式,您可能还必须使用value_method选项并将其设置为team_id才能正确设置它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM