Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

rails undefined method `each' for #<Field

I have a form that allows user to register for a tournament. In the process of building the registration form I hae dynamic nested fields with so far field_type of basic. When I load the participants new form I am trying to load all the fields from the Fields table with field_type of basic. It will find them and if I just try <%= @basic.name %> from the new form it will give the name of the last field in the database with that field_type, but if I try:

<% @basic.each do |b| %>
  <%= b.name %>
<% end 

I get the error undefined method `each' for #<Field.

Here is the new action from the participants_controller:

def new
    @participant = @event.participants.new
    @user = User.find(current_user.id)
    @children = @user.children
    @basic = Field.find_by(event_id: @event.id, field_type: 'basic')
  end

Fields belong to events but do I have to connect them to participants to make this work?

Thanks

question from:https://stackoverflow.com/questions/65911730/rails-undefined-method-each-for-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

find_by only returns a single record (or nil if the criteria aren't matched) use where to return a collection.

@basic = Field.where(event_id: @event.id, field_type: 'basic')

However assuming you have the association has_many :fields defined in Event you could also use:

@basic = @event.fields.where(field_type: 'basic')

And if you have the scope :basic, -> { where(field_type: 'basic') } defined in Field you can further simplify to:

@basic = @event.fields.basic

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...