Amr Amr - 2 months ago 9
Ruby Question

Ruby on Rails checking object before instantiate it

I have two models X and Y, X has many Y, Y belongs to X.

At Y controller i need to add a method that constrain the ability of X to see or edit any other Y but it's related one.

Lets say i created an object x1 that connected 3 different Y
and x2 that connected to 4 other different Y
at show page if i call any y by id i'll get it regardless

session[x.id]
is
i need to compare
x.id
with
y.x_id


if they are equal return true
the problem that i need to do that before instantiate the y object
i don't want to use any gems
if any one can help i'll deeply appreciate it.

thank you

Answer
def show
  @y = Y.find(params[:id])

  unless @y.x.id == session(x.id)
    render status: :forbidden, text: 'You are not allowed here!' and return
  end
end