当前位置: 动力学知识库 > 问答 > 编程问答 >

Scope of each on rails template

问题描述:

I'm new to rails and I'm trying to build a view that will list the parents and related children

Ex:

Passport has many Visas

I want to list information about the passport and the visas that the passport has.

So I have

<% @passport_list.each do |passport| %>

# passportFields

<% passport.visas.each do |visa| %>

<%= t.text_field :visa_type %>

<% end %>

<% end %>

I'm getting the error

undefined method `visa_type' for #Passport:0x000000091b8b28

It looks like rails is trying to find the property visa_type for passport, instead of in visa. How does the scope work within each? Can I force it to access visa_type from visa?

网友答案:

I think you're looking for the fields_for form helper. This will allow you to create fields for the relevant visa attributes. Replace your code sample with the following, and you should be all set.

<% @passport_list.each do |passport| %>
  # passportFields
  <% t.fields_for :visas do |visa_fields| %>
    <%= visa_fields.text_field :visa_type %>
  <% end %>
<% end %>

You can also iterate over the list as follows:

<% @passport_list.each do |passport| %>
  # passportFields
  <% passport.visas.each do |visa| %>
    <% t.fields_for :visas do |visa_fields| %>
      <%= visa_fields.text_field :visa_type %>
    <% end %>
  <% end %>
<% end %>

For more information on fields_for, check out the link I added above, and to customize further for your use case, check out the "One-to-many" section.

网友答案:

IMO you should always handle the null case of an object.

Something like this if you use rails (present? is a Rails function)...

<% if @passport_list.present? %>
  <% @passport_list.each do |passport| %>
     passportFields
     <% passport.visas.each do |visa| %>
         <%= t.text_field :visa_type %>   
     <%end%>

  <%end%>
<% else %> 
 <p>Nothing to see here</p>
<% end %>

However if your @passport_list is backed by an ActiveRecord Query, you can handle this in the model/helper/controller by returning the .none query on the model. Note that this differs from an empty array because it is an ActiveRecord Scope, so you can chain AR queries onto it

# scope on AR model
def self.awesomeville
  where(country_of_origin: "awesomeville")
end

# method queried in controller
@passport_list = Passport.all
if @passport_list.present? 
  @passport_list
else 
  Passport.none
end 

# additional filtering in view is now possible without fear of NoMethodError
@passport_list.awesomeville

Whereas a ruby Array would raise an error as it would respond to the Array methods.

分享给朋友:
您可能感兴趣的文章:
随机阅读: