Having a many-to-many relationship in a view.

I have a link to the stack overflow post [here](http://www.reddit.com/r/learnprogramming/comments/1trffs/ruby_on_rails_blockbuster_demo_application/), but the main idea, is that if I have two models that interact with each other in a `has_many :through` way, using a join table, how do I create both objects in one view?

Thanks!

1 thought on “Having a many-to-many relationship in a view.”

  1. Let’s say you have a Worker model and a Task model, which have_many of each other through an Assignment model. In your view you can do something like:

    @worker.name

    @worker.title

    <%= render partial: "worker_tasks", collection: @worker.tasks, as: :task %>

    Then you have a partial called “_worker_tasks.html.erb” (note the leading underscore):

    task.name

    task.description

    Your controller would have to set @worker.

    Alternatively, you can have your controller set

    @worker = Worker.find(params[:id])

    and have it also set

    @tasks = @worker.tasks

    and then you don’t need a partial, but I prefer to use a partial because it is neater and I can reuse it elsewhere in my app.

    Does this help?

    **EDIT:**

    You can also simplify the *render* call by just using:

    <%= render @tasks %>

    and you would need to have a partial called “_task.html.erb” and it would pass each object in @tasks to the partial as “task”, so you can still do

    task.name

    in the partial. I only used the original syntax b/c I had multiple partials and needed to call a specific one that was not named “tasks”.

    Reply

Leave a Comment