在连接模型中设置属性

发布于 2024-09-25 02:46:10 字数 532 浏览 2 评论 0原文

我有以下用户模型:

class User < ActiveRecord::Base

  has_many :competences
  has_many :skills, :through => :competences

  accepts_nested_attributes_for :skills
end

和以下技能模型:

class Skill < ActiveRecord::Base
  has_many :competences
  has_many :users, :through => :competences
end

能力模型有一个“类型”属性,它是连接模型。在嵌套表单中,如何在保存提交的技能时设置“类型”属性? 这是嵌套形式:

<% f.fields_for :skills  do |s| %>
   <%= s.text_field :name %>
<% end %>

I have the following User model:

class User < ActiveRecord::Base

  has_many :competences
  has_many :skills, :through => :competences

  accepts_nested_attributes_for :skills
end

and the following Skill model:

class Skill < ActiveRecord::Base
  has_many :competences
  has_many :users, :through => :competences
end

The Competence model has a 'type' attribute and it is the join model. Inside the nested form, How can I set the 'type' attribute while I save the submitted skills?
Here is the nested form:

<% f.fields_for :skills  do |s| %>
   <%= s.text_field :name %>
<% end %>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寂寞美少年 2024-10-02 02:46:10

您需要专门创建 Competence 对象 - 您不能隐式创建它(如 HABTM)并为其设置属性。

@user.competences.create(:type => 'something', :skill => @skill)

您的用户模型应该接受能力的嵌套属性,它应该接受技能的嵌套属性。像这样的事情应该会让你走上正轨:

<% f.fields_for :competences do |c| %>
  <%= c.text_field :type %>
  <% c.fields_for :skills do |s| %>
    <%= s.text_field :name %>
  <% end %>
<% end %>

You need to create the Competence object specifically -- you can't implicitly create it (a la HABTM) and also set attributes on it.

@user.competences.create(:type => 'something', :skill => @skill)

Your User model should accept nested attributes for Competences, which should accept nested attributes for Skills. Something like this should put you on the right track:

<% f.fields_for :competences do |c| %>
  <%= c.text_field :type %>
  <% c.fields_for :skills do |s| %>
    <%= s.text_field :name %>
  <% end %>
<% end %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文