Maira Muneer Maira Muneer - 4 months ago 8
Ruby Question

Associations in Rails 4

I am developing a web application for task management using ruby on rails.
I have two models

user
and
task
. The models look like this

class User < ActiveRecord::Base
has_many :tasks
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

def role?(role_name)
role == role_name
end

def self.assigned_user(task_params)
User.where("name = ?", task_params["assigned_to"])
end
end



class Task < ActiveRecord::Base
belongs_to :user
end


what i want is assign task to user when a task is created. But i don't know how to do it in
create
action of
tasks_controller
. My create action looks like this

def create
@task = Task.new(task_params)
respond_to do |format|
if @task.save
@user = User.assigned_user(task_params)
@user.tasks << Task.last
format.html { redirect_to @task, notice: 'Task was successfully created.' }
format.json { render :show, status: :created, location: @task }
else
format.html { render :new }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end


Whenever admin assigns a task when its created, it gives an error saying
undefined method tasks for #<User::ActiveRecord_Relation:0x007fe7b1c60610>
. Does anyone can help what can be the problem with this?

Answer

The error it is giving you is because the where method is returning a collection of users and you want just one user:

def self.assigned_user(task_params)
  User.where("name = ?", task_params["assigned_to"]).first
end

You probably want to revise your code as I guess you could have problems if name is not unique. Make sure the field you use to retrieve the user is unique.

The code for creation can look like this:

def create
  @task = Task.new(task_params)
  respond_to do |format|
    if @task.save
      @user = User.assigned_user(task_params)
      @user.tasks << @task
      format.html { redirect_to @task, notice: 'Task was successfully created.' }
      format.json { render :show, status: :created, location: @task }
    else
      format.html { render :new }
      format.json { render json: @task.errors, status: :unprocessable_entity }
    end
  end
end
Comments