Search code examples
ruby-on-railsmany-to-manyrelationships

how to create relationships many to many from array of users


I get a couple of user objects in @users. and i have a task object in params[:task] Now i want to save the taskobject and add relationships between all @users and that task....

@users = User.find(session[:user_id], params[:user_task])
@task = @users.tasks.create(params[:task])
@task.owner_id = session[:user_id]      

if @task.save
  redirect_to task_path(@task)

all i get is an error like: undefined method `tasks' for Array. How do i do it?


Solution

  • You need to first initialize the new task, assign its owner and save it, and if that is successful then you can create associations with all users.

    Like this:

    @task = Task.new(params[:task])
    @task.owner_id = session[:user_id]
    if @task.save
      @users = User.find(session[:user_id], params[:user_task])
      @users.each { |user| user.tasks << @task }