RoR: how can I search only microposts with a certain attribute?

廉价感情. 提交于 2020-01-06 05:42:12

问题


Right now in app/views/microposts/home.html.erb I have..

<% form_tag purchases_path, :method => 'get', :id => "products_search" do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

<% form_tag sales_path, :method => 'get', :id => "sales_search" do %>
      <p>
        <%= text_field_tag :search, params[:search] %>
        <%= submit_tag "Search", :name => nil %>
      </p>
    <% end %>

and then in micropost.rb I have

scope :purchases, where(:kind => "purchase")
  scope :sales, where(:kind => "sale")

 def self.search(search)
    if search
      where('name LIKE ?', "%#{search}%")
    else
      scoped
    end
  end

and then finally in the microposts_controller.rb I have

def home

    @microposts=Micropost.all
    @purchases=@microposts.purchases
    @sales=@microposts.sales

  end

Right now I am getting an error saying undefined local variable or method `purchases_path' and it does the same for sales_path.

What I want to be able to do is search only some of the microposts instead of all of them. In my micropost table I have a column called kind which can be either "purchase" or "sale". How can I change these three pieces of code so that one search searches through and displays results for only those microposts with the kind "purchase". And then the other searches through and displays results for only those microposts with the kind "sale"

this question (on another post) has a bounty with 50 rep at RoR: how can I search only microposts with a specific attribute?


回答1:


You might try this.

Your model:

class Micropost
  # ...
  scope :purchase_only, where(:kind => "purchase")
  # ...
  def self.search(search)
    if search
      self.purchase_only.find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
    else
      self.purchase_only
    end
  end
end

But, this stuff looks very strange to me.

E.g.: You should remove the .find(...), this finder will be deprecated with Rails 4.



来源:https://stackoverflow.com/questions/12611866/ror-how-can-i-search-only-microposts-with-a-certain-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!