D
D
dexdev2014-08-27 20:58:49
Ruby on Rails
dexdev, 2014-08-27 20:58:49

How to correctly select data?

I’m back)
In general, the situation is as follows, I can’t figure out what the problem is, there are posts posts have a city, it is necessary that there is a choice by city, but something doesn’t work for me)
posts_controller.rb

def post_all
    @posts = Post.all.paginate(page: params[:page])
    @posts = Post.where(status: params[:status]).paginate(page: params[:page]) if params[:status].present?
    @posts = Post.where(city_id: params[:city_id]).paginate(page: params[:page]) if params[:city_id].present?
  end

and in the sky I indicate
<%= form_for all_post_path, :method => 'get' do |f| %>
          <%= f.collection_select :city_id, City.all, :id, :name, :prompt => "Выберите город" %>
          <%= render @posts %>
  				<%= submit_tag "Search", :name => nil %>
  				<% end %>

post.rb
belongs_to :city
city .rb
has_many :posts
Still shows absolutely all posts

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vsuhachev, 2014-08-28
@AdilA

You have problems with logic, it must be something like this

def post_all
  @posts = Post.all
  @posts = @posts.where(status: params[:status]) if params[:status].present?
  @posts = @posts.where(city_id: params[:city_id]) if params[:city_id].present?
  @posts = @posts.paginate(page: params[:page])
end

And apparently there is still a problem with the parameter name. Check your code by entering ?city_id=111 in your browser's address bar. Take a look at development.log, make sure the query parameter name is city_id and not posts[city_id].

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question