0

Model Cafe has meal_available, which has boolean type.

When searching cafe, I want to re-search by category checkbox:

<form action="/cafe/cafesearch" method="GET">
<label for="chk1"><input type="checkbox" id="chk1" name="meal_available" value=true>meal_available</label>
<input type="submit" value="submit">
</form>

At view, pass checkbox value through form tag, and at controller, I tried like this:

coffee = Cafe.all
if params[:meal_available] == true
  @cafe = coffee.delete_if{|x| x.meal_available == false}
end

It didn't work. How can I delete element by model column in array?

0

2 Answers 2

1

You can just put in a scope in Cafe model to get the cafes with meal_available, more information on ActiveRecord scopes here

In cafe model :

class Cafe < ActiveRecord::Base
  scope :meals_available, -> { where(meal_available: true) }
end

In controller :

@cafes = Cafe.meals_available

thats it, thanks.

Sign up to request clarification or add additional context in comments.

5 Comments

it is not answer on question. Question is How delete element?
@Ilya if you read the question and code properly again you will get it right. Sangwoo Park is trying to search through the records in the controller and only wants to get the cafes with meal_available: true and scopes is a better options for that.
delete was just to reject the cafes with meal_available: false scopes would work better in these situation
Scope is a good solution, but you did not answer on main question. Author attempts to delete records from database.
I must agree with @sghosh968 here. OP is asking for deleting items in an array, not the database. Manipulating the database on each page reload on a search action (which is triggered by a GET request) doesn't make any sense. The only reason OP accepted the above answer is b/c it has the same outcome as asked for. +1
0

You can use ActiveRecord methods for it only:

if params[:meal_available] == true
  @cafe = Cafe.where(meal_available: false)
end

In this case coffee = Cafe.all is redundant.

coffee = Cafe.all
if params[:meal_available] == true
  @cafe = coffee.select { |x| x.meal_available == false }
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.