2015-10-14 38 views
1

我在这里我的应用程序来解决一点简短的问题:
我的应用程序是一样的东西制作的Airbnb,所以我有UsersHouses,任何用户都可以创建一所房子我已经有这个,我需要一个观察名单,是一个用户喜欢的书签或收藏系统的房屋列表,我有房子列表,并且当用户点击这个房子时,这个想法有像“观看这个”的按钮进入他们的观察名单。
我见过很多的解决方案和我试图他们,我理解的关系,但我不知道怎么弄条 这里是目前我的代码:创建在轨的最爱列表与色器件

watch.rb:

class Watch < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :house 
end 

user.rb:

class User < ActiveRecord::Base 
    has_many :houses, :dependent => :destroy 
    has_many :watches, :dependent => :destroy 
    has_many :watch_houses, :through => :watches, :source => :houses 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
end 

house.rb:

class House < ActiveRecord::Base 
    belongs_to :user 
    has_many :watches, :dependent => :destroy 
    has_many :watches, :through => :watches, :source => :user 
end 

routes.rb:

Rails.application.routes.draw do 
    resources :houses 
    devise_for :users 
    resources :users, :only => [:show] do 
     resources :watches 
    end 
    resources :houses 
    root 'home#index' 
end 

如何创建一个链接到assing在监视列表cliking用户和房子的房屋列表?

回答

0

这里是如何做到这一点:

#config/routes.rb 
resources :houses do 
    post :watch #-> url.com/houses/:house_id/watch 
end 

#app/controllers/houses_controller.rb 
class HousesController < ApplicationController 
    def watch 
     @house = House.find params[:house_id] 
     current_user.watched_houses << @house 
     redirect_to @house, notice: "Added to Watch List" 
    end 
end 

下面是型号:

#app/models/user.rb 
class User < ActiveRecord::Base 
    has_many :houses, dependent: :destroy 
    has_many :watching, class_name: "Watch", foreign_key: :user_id, dependent: :destroy 
    has_many :watched_houses, through: :watching 
end 

#app/models/house.rb 
class House < ActiveRecord::Base 
    belongs_to :user 
    has_many :watches, dependent: :destroy 
    has_many :watchers, through: :watches, foreign_key: :user_id 
end 
+0

谢谢!但现在我创建LIK看房子'​​<%=的link_to“观看',house_watch_path(房子),方法:: post%>'但我得到这个错误'无法找到源关联(s)“watched_house”或:Watched_houses模型观察。尝试'has_many:watched_houses,:through =>:watching,:source =>'。它是用户还是家中的一员?“你知道吗? – Icaro