Rails中的嵌套表单-has_many关系中的访问属性 [英] Nested forms in rails - accessing attribute in has_many relation

查看:67
本文介绍了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中的嵌套表单-has_many关系中的访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆