简体   繁体   中英

How to access join table attributes (has_many :through) from association

I'm trying to create records list with the attributes of the associated records. Get Task goal Attribute inherit \\ replace Power - goal Attribute

if we have:

@tasks = user.tasks

when we render the view

<%= render @tasks %>

Everything is fine, we can just use <%= task.goal %> in the partial and all working, but if we have user.super_tasks how to override goal in the partial?

The first thing that comes to mind is to make in the _task.htm.erbl

<%= goal = if @super_tasks then task.powers.find_by(user_id: current_user).goal else task.goal end %>

It's kind of make it, but this ok if you have 3 records, with 15 it will make 15 request to db to find the join table each time.

Just added the tables to make it more clear:

class User < ActiveRecord::Base
   has_many :tasks
   has_many :powers
   has_many :super_tasks , through: :powers, source: :task
end

class Task < ActiveRecord::Base
   belongs_to :user
   has_many :powers
end

class Power < ActiveRecord::Base
   belongs_to :user
   belongs_to :tasks 
end

But if user have power they have more responsibilities, its not the first time that I stuck on that problem, for sure there is other way to make this work without calling the db each time, as it sadly common problem.

Ok maybe it not the best solution, but it works and answers the question:

tasks = user.tasks.order(:id)
power_tasks = user.powers.order(:task_id)

tasks.each_with_index do |task,i|
    task.goal = power_tasks[i].goal 
end

The weak point if this code is, if we say there is no task_id to order \\ adjust the power or if the number power_tasks does not match the tasks. But for my case it worked perfectly.

If you want to added other param, that not exist on normal Task , but exist on Power table and you want to added it to tasks also, then in the model we can:

class Task < ActiveRecord::Base
   attr_accessor :cookies

task.cookies = power_tasks[i].cookies

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