【问题标题】:Rails Form with belongs_to Association带有 belongs_to 关联的 Rails 表单
【发布时间】:2015-08-29 23:58:28
【问题描述】:

我对 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

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

【问题讨论】:

  • 如果用户属于一个团队,它应该有一个team_id,因为belongs_to在外键的一边?此外,除非您在哪里使用嵌套属性做某事,否则您不需要 fields_for。
  • 对不起,我并不完全了解 belongs_to 关联的实际运作方式,你说得对。谢谢!

标签: ruby-on-rails forms belongs-to


【解决方案1】:

欢迎使用 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 %>

【讨论】:

    【解决方案2】:

    使用 gem https://github.com/plataformatec/simple_form 很容易做到这一点

    协会

    为了处理关联,Simple Form 可以生成选择输入、一系列单选按钮或复选框。让我们看看它是如何工作的:假设您有一个属于公司的用户模型和 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 %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多