开发者

Undefined Method in form

开发者 https://www.devze.com 2023-01-30 02:00 出处:网络
class User has_one :user_profile end class UserProfile belongs_to :user end I am rendering a form for editing the user\'s account:
class User
    has_one :user_profile
end
class UserProfile
    belongs_to :user
end

I am rendering a form for editing the user's account:

<%= form_for current_user do |f| %>
<%= f.text_field current_user.user_profile.first_name %>
<%= end %>

But that throws an error:

NoMethodError in Account#edit
undefined method `Andy' for #<开发者_如何学JAVAUser:0x5f375e8>

Why is the value of the first_name being used?

How do I fix this (without using a partial) ?

Also, if someone could guide me to either a book or some comprehensive online tutorials for using forms (and nested forms) in Rails, I would highly appreciate it. Forms are driving me nuts!


The first argument to the text_field helper is a symbol naming the model object's attribute. So in your case it should be:

<%= form_for current_user.user_profile do |f| %>
  <%= f.text_field :first_name %>
<% end %>

If your form needs to edit both the User and UserProfile model objects, you'll need fields_for to switch context.

<%= form_for current_user do |f| %>
  <%= f.text_field :some_user_attribute %>
  <%= f.fields_for current_user.user_profile do |f| %>
    <%= f.text_field :first_name %>
  <% end %>
<% end %>

See: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for

0

精彩评论

暂无评论...
验证码 换一张
取 消