Rails 表单与 belongs_to 关联

Rails Form with belongs_to Association

我是 Rails 的新手,所以这可能是一个明显的问题,如果是这样,我深表歉意。

我正在尝试创建一个用于创建 User 记录的表单,该记录与 Team 模型有 belongs_to 关联。到目前为止我所做的是以下...

<% form_for @user, url: {action: "create"} do |f| %>
  <%= f.text_field :name %>
  <%= f.text_field :email %>

  <% f.fields_for :team do |team| %>
    <%= team.collection_select(:team_id, Team.all, :id, :name) %>
  <% end %>
  <%= f.submit %>
<% end %>

这似乎工作得很好,但是在创建用户记录时我 运行 遇到了麻烦。

def create
  @team = Team.find(params[:user][:team][:team_id])
  @team.users.create(user_params)
  # Ignoring error checking for brevity
end

def user_params
    params.require(:user).permit(:name, :email)
end

params 现在包含 team_id 的字段,它不是 User 模型的属性,因此创建失败。我不确定如何着手解决这个问题,更不用说这是否是解决这个问题的合适方法了。任何建议将不胜感激!

欢迎来到Rails :)

如果目标是确保每个用户都可以成为团队的一部分,那么以这种方式进行关联的逻辑没有问题。

因此,首先您需要确保 team_id 存在于用户模型中。而且,正如 Doon 所建议的,您不需要 fields_for 除非您想与团队模型进行交互并从同一表单中进行更改。

所以首先创建一个迁移 rails g migration add_team_to_user team:belongs_to

在您的迁移中使用 belongs_to 将添加一个引用,您可以在此处了解:http://edgeguides.rubyonrails.org/active_record_migrations.html

然后迁移你的数据库 bundle exec rake db:migrate

并重新启动您的服务器。然后像这样更改您的表格:

<% form_for @user, url: {action: "create"} do |f| %>
  <%= f.text_field :name %>
  <%= f.text_field :email %>
  <%= f.collection_select(:team_id, Team.all, :id, :name) %>

  <%= f.submit %>
<% end %>

使用 gem https://github.com/plataformatec/simple_form

很容易做到这一点

协会

为了处理关联,Simple Form 可以生成 select 输入、一系列单选按钮或复选框。让我们看看它是如何工作的:假设您有一个属于公司和 has_and_belongs_to_many 角色的用户模型。结构类似于:

class User < ActiveRecord::Base
  belongs_to :company
  has_and_belongs_to_many :roles
end

class Company < ActiveRecord::Base
  has_many :users
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end

现在我们有了用户表单:

<%= simple_form_for @user do |f| %>
  <%= f.input :name %>
  <%= f.association :company %>
  <%= f.association :roles %>
  <%= f.button :submit %>
<% end %>