Rails中的嵌套表单

编程入门 行业动态 更新时间:2024-10-27 18:31:33
本文介绍了Rails中的嵌套表单-has_many关系中的访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个用户和一个个人资料模型.一个用户可以有多个配置文件.在用户创建过程中,我只需要访问我的用户模型中个人资料"部分中的一个信息(即电话号码).因此,我试图通过attr_accessible完成它.我的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

我面临的问题是,当我尝试在user.rb中的方法中调用getter方法profile_mobile_number时(该方法是私有的,尽管我认为这没关系),我得到的是null价值.我在users/new.html.erb表单中使用以下内容

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

我的问题是执行此操作的正确方法是什么?我应该使用<% f.fields_for :profile do |ff| -%>还是<% f.fields_for :profiles do |ff| -%>(请注意,第二个是复数).当使用复数:profiles时,我什至看不到表单上的字段.我在这里想念什么?在模型user.rb中需要使用什么时态? :profile_phone_number或:profiles_phone_number?谢谢.

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.

推荐答案

您可以执行以下操作:

<% form_for @user, :url => { :action => "update" } do |user_form| %> ... <% user_form.fields_for :profiles do |profiles_fields| %> Phone Number: <%= profiles_fields.text_field :profile_mobile_number %> <% end %> <% end %>

但是由于您已经有关联,因此不妨使用' accepts_nested_attributes_for '

But since you already have an association, then might as well use 'accepts_nested_attributes_for'

更多推荐

Rails中的嵌套表单

本文发布于:2023-10-18 06:04:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1503349.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   表单   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!