I have a User who has Clients, and Clients have Expenses. I have a form that creates a new expense and on that form the user needs to select which client the expense is for. Here's how I did it:
= form_for(@expense) do |f|
...
= f.select :client_id, options_from_collection_for_select(@possible_clients, "id", "name"), {:include_blank => true}, :class => "span10"
and the controller:
def create
@expense = Expense.new(params[:expense])
@expense.user = current_user
@expense.date = convert_to_db_date(params[:expense][:date])
respond_to do |format|
if @expense.save
format.html { redirect_to expenses_path }
format.json { render json: @expense, status: :created, location: @expense }
else
format.html { render action: "new" }
format.json { render json: @expense.errors, status: :unprocessable_entity }
end
end
end
and the expense model:
belongs_to :client
belongs_to :user
belongs_to :invoice
## ACCESSIBLE ##
attr_accessible :amount, :category, :date, :invoice_id, :note, :reimbursed, :user_id, :client_id
and the client model:
belongs_to :user
has_many :contacts, :dependent => :destroy
has_many :invoices
has_many :expenses
So I'm just thinking there's a big security issue here. Since a user can submit any id for the client associated with the expense...they can assign any client, right? Is there a better way of doing this? Is there some rails magic that prevents security issues?
@expense.user = current_user
. If you pass auser_id
, do you have a problem or not? Seems to be the easiest way to tell. Use a firefox extension to issue a post if you don't know how to do it manually, or a hidden field. – fotanus Apr 16 '13 at 3:08