简体   繁体   中英

How to loop through multiple polymorphic models?

I don't know how to make a loop that goes through 2 models apart of the polymorphic association I have. I have the models User , Follow , Dad and Mom .

class User
 has_many :follows
end

class Mom
  has_many :follows, as: :followable
  # columns: name, :address
end

class Dad
  has_many :follows, as: :followable
  # columns: name
end

class Follow
 belongs_to :user
 belongs_to :followable, polymorphic: true
 # columns: user_id, followable_id, followable_type
end

My goal is to loop through the moms and dads that the user is following and get there specific attributes like this:

# FollowsController

index
 # follows = dads and moms
 @follows = current_user.follows.paginate(page: params[:page])
end

# follows/index.html.erb

<% @follows.each do |f| %>
 <%= f.dad.name %>
 <%= f.mom.name %>
 <%= f.mom.address %>
<% end %>

How would this be done?

You just need to use

f.followable.name
f.followable.address

If you want to check if it is dad or mom then you can check it like this

f.followable_type == 'Dad'

Or

f.followable.kind_of?(Dad)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM