Question

I need to create a CRUD that allow create and update projects and one of the attributes is the client that owns the project. When the project is created or edited, the client is selected using a select tag.

I have this model:

class Cliente < ActiveRecord::Base
  attr_accessible :nombre
  has_many :proyectos
end

class Proyecto < ActiveRecord::Base
  attr_accessible :nombre, :cliente_id
  belongs_to :cliente
end

this controller:

class ProyectosController < ApplicationController
  def new
    @proyecto = Proyecto.new
    @clientes = Cliente.order(:nombre)
  end

  def edit
    @proyecto = Proyecto.find(params[:id])
    @clientes = Cliente.order(:nombre)
  end

  def create
    @proyecto = Proyecto.new(params[:proyecto])
      if @proyecto.save
        redirect_to @proyecto, notice: 'Proyecto was successfully created.'
      else
        render action: "new"
      end
    end
  end

  def update
    @proyecto = Proyecto.find(params[:id])
    if @proyecto.update_attributes(params[:proyecto])
        redirect_to @proyecto, notice: 'Proyecto was successfully updated.'
      else
        render action: "edit"
    end
  end
end

and this form on the view (in haml):

= form_for @proyecto do |f|
  = f.label :cliente
  = f.collection_select :cliente_id, @clientes, :id, :nombre
  = f.label :nombre
  = f.text_field :nombre
  = f.submit 'Save'

The code was generated with scaffold, I just removed the unnecesary parts and added the code to create the select.

Initially, on the model Proyecto I had this:

attr_accessible :nombre

but get the error "Can't mass-assign protected attributes: cliente_id". Searching here on stackoverflow for similar problems, I found that I must add cliente_id to attr_accessible, but searching on google also found that I must not add foreing keys to attr_accessible due to security issues, which is contradictory.

Is this the correct way to code my create and update methods, adding cliente_id to attr_accessible? If not, what is the correct way?

I'm working with rails 3.2.8 and ruby 1.9.3p194

Was it helpful?

Solution

In this case you must have the client_id as attr_accessible. The reason is because you are allowing the user to set the client through the select box on the form.

However, this poses a security concern. Imagine that you are only showing a specific user 3 different clients he can pick from (IDs: 1, 2, 3). If the user modifies the form manually, he can assign a client with ID #4 to his project which can be a security issue or just a bug.

To close the security issue, add a validation to your Project model that makes sure that the client ID is valid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top