我的书中有一个使用pg_search的模型,在搜索中我希望能够通过用户名搜索书籍。在我的book.rb模型中,我有以下内容:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// How many sections. Means numberOfSections * rows = view
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
// Defines the number of rows in a section table
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return 1
}
// Defines contet of each cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
//let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! myCell
var countries = ["Turkey","Croatia","USA"]
var logoImageTUR = UIImage(named: "turkey.png")
var logoimageCRO = UIImage(named: "croatia.png")
var logoimageUSA = UIImage(named: "USA.png")
var countryLogos = [logoImageTUR, logoimageCRO, logoimageUSA]
for var i = 0; i < 2; i++
{
cell.lbl_countryName.text = countries[i]
cell.img_countryFlag.image = countryLogos[i]
return cell
}
}
以上代码适用于我书中的任何内容,但我需要做的是找到与该书相关联的用户名。我的架构我将user_id附加到books表,我可以在我的视图和模型 include PgSearch
pg_search_scope :search, :against => [:title, :age, :story_types, :slug, :synopsis, :body, :user],
associated_against: {
user: [:name]
},
using: { tsearch:{ dictionary: "english" } }
belongs_to :user
belongs_to :gallery
has_many :stories
has_many :images
has_many :reviews
has_and_belongs_to_many :schools, join_table: "books_schools"
accepts_nested_attributes_for :user
accepts_nested_attributes_for :gallery, :allow_destroy => true
accepts_nested_attributes_for :schools, :allow_destroy => true, :reject_if => :find_school
accepts_nested_attributes_for :images, :allow_destroy => true
def self.text_search(query)
if query.present?
where("title @@ :q or synopsis @@ :q or age @@ :q", q: query)
else
scoped
end
end
中获取该书的用户详细信息,然后获取我刚才的名称@book_author = User.where("id = '#{@book.user_id}'")
我知道有些人可能会说这很奇怪,但书籍保存的方式对我来说是合乎逻辑的。
任何人都可以尝试帮我开始寻找合适的地方。我确信它非常简单但很难让我理解。
干杯
答案 0 :(得分:-1)
使用委托http://apidock.com/rails/Module/delegate 在book.rb中添加以下行
delegate :name, :to => :user, ;prefix => true
在视图中执行以下操作
<%= @book.user_name %
取代。
@book是一个Book实例
即使您不想使用委托,也可以轻松完成以下操作
<%= @book.user.name %
&GT;
如果您提交控制器并查看代码以获得更多帮助,那就太棒了。