使用设计

时间:2015-10-14 14:02:19

标签: ruby-on-rails ruby-on-rails-4 devise

我有一个问题需要在我的申请中解决一下这个简短的说明:
我的应用程序类似于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

如何创建一个链接,以帮助用户和监视列表中的房子在房屋清单中出现?

1 个答案:

答案 0 :(得分: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