RoR:如何只搜索具有特定属性的微博? [英] RoR: how can I search only microposts with a certain attribute?

查看:32
本文介绍了RoR:如何只搜索具有特定属性的微博?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在在 app/views/microposts/home.html.erb 我有..

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 %>

然后在 micropost.rb 我有

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

然后最后在 microposts_controller.rb 我有

and then finally in the microposts_controller.rb I have

def home

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

  end

现在我收到一条错误消息,说未定义的局部变量或方法purchases_path",它对 sales_path 也是如此.

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

我想要做的是只搜索一些微博而不是所有微博.在我的微博表中,有一个名为 kind 的列,可以是购买"或销售".如何更改这三段代码,以便一次搜索搜索并仅显示具有购买"类型的微博的结果.然后另一个搜索并只显示那些类型为sale"的微博的结果

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"

这个问题(在另一篇文章中)在 RoR:如何只搜索具有特定属性的微博?

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

推荐答案

你可以试试这个.

您的模型:

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.

例如:您应该删除 .find(...),此查找器将在 Rails 4 中弃用.

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

这篇关于RoR:如何只搜索具有特定属性的微博?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆