Rails 中的嵌套表单 - 访问 has_many 关系中的属性
我有一个用户和一个配置文件模型。一个用户可以拥有多个配置文件。在用户创建过程中,我只需要访问用户模型中配置文件部分的一项信息(即电话号码)。因此我试图通过 attr_accessible 来完成它。我的 user.rb 看起来像这样。
has_many :profiles
attr_accessible :handle, :email, :password, :profile_mobile_number
attr_accessor : :profile_mobile_number
我面临的问题是,当我尝试在 user.rb 中的方法中调用 getter 方法 profile_mobile_number (该方法是私有的,尽管我认为这并不重要)时,我得到一个 null 值。我在 users/new.html.erb 表单中使用以下内容
我的问题是正确的方法是什么?我应该使用 <% f.fields_for :profile do |ff| -%>
或 <% f.fields_for :profiles do |ff| -%>
(注意第二个是复数)。当我使用复数 :profiles 时,我什至看不到表单上的字段。我在这里缺少什么?模型 user.rb 中需要使用什么时态? :个人资料电话号码或:个人资料电话号码?谢谢。
I have a user and a profile model. One user can have many profiles. I need to access only one information from the profiles section (viz the phone number) in my user model during the user creation process. Hence I'm trying to get it done through attr_accessible
. My user.rb looks like this.
has_many :profiles
attr_accessible :handle, :email, :password, :profile_mobile_number
attr_accessor : :profile_mobile_number
The problem that I'm facing is that when I try to call the getter method profile_mobile_number in a method in user.rb (the method is private, though I think it doesn't matter), I'm getting a null value. I use the following in my users/new.html.erb form
My question is what is the right way to do this? Should I use <% f.fields_for :profile do |ff| -%>
or <% f.fields_for :profiles do |ff| -%>
(notice that the second one is plural). When I use the plural :profiles, I don't even see the fields on the form. What am I missing here? And what is the tense that needs to be used in model user.rb? :profile_phone_number or :profiles_phone_number? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以执行如下操作:
但是既然您已经有了关联,那么不妨使用 'accepts_nested_attributes_for'
You could do something like the following:
But since you already have an association, then might as well use 'accepts_nested_attributes_for'
您应该观看RailsCasts 嵌套模型表单。
感谢 Ryan Bates 出色的工作。
You should watch RailsCasts Nested Model Form.
thanks Ryan Bates great work.
http://apidock.com/rails/v3.2.8/ActionView/Helpers /FormHelper/fields_for
此 api 停靠链接列出了许多嵌套属性示例,包括一对一、一对多。这非常有帮助!
http://apidock.com/rails/v3.2.8/ActionView/Helpers/FormHelper/fields_for
This api dock link list many Nested Attributes Examples including one-to-one, one-to-many. It's very helpful!
您可以使用“accepts_nested_attributes_for”来执行此操作;但表单中有一个小技巧:
您必须使用单数,并为每个配置文件调用 fields_for,如下所示:
请注意,这是 :profile_attributes,而不仅仅是 :profile。
You can use 'accepts_nested_attributes_for' to do this; but there's a little trick in forms:
You must use the singular, and call fields_for for each profile, like this:
Notice that is :profile_attributes, instead of just :profile.