在没有Ajax或jQuery on Rails的情况下类似/不同



我正在尝试实现一个简单的类似/不同函数。我在这里看到的所有示例似乎都适用于ajax或jquery。我还是一个初学者,我还不完全理解,我只想要一个简单的解决方案。

我的想法是,我有书,我有用户。用户可以喜欢书。因此,我通过Like模型创建了一个多对多关联。Like模型有一个相应的数据库,其中包含book_id和user_id列。因此:

class Book < ActiveRecord::Base
  has_many :likes
  has_many :users, through: :likes
class User < ActiveRecord::Base 
  has_many :likes
  has_many :books, through: :likes
class Like < ActiveRecord::Base
  belongs_to :book
  belongs_to :user
end

不幸的是,这是我所能理解的。我不知道如何利用这种关系来创建点赞,并将其与合适的书籍和用户联系起来。

我的想法是,如果用户不喜欢这本书,就给他一个"点赞"按钮,或者如果他不喜欢,就给用户一个"不同"按钮。所以基本上,我想要一个简单的东西:

<%  if user likes? %>
<div class="unlike_button"><%= link_to "Unlike", '#' %></div>
<% else %>
<div class="like_button"><%= link_to "Like", '#' %></div>
<% end %>

我使用了#存根,因为我不知道它应该使用什么路由。但无论解决方案是什么,我都希望它重定向到同一个页面,并附上一条闪烁的通知,上面写着"喜欢"或"不同"。我已经为like_button和unlike_button类提供了div背景图像,这就是为什么我将它们实现为上面的图像链接。

任何形式的指导或帮助,我们都将不胜感激。感谢

更新

我在下面遵循本尼克的指导,但我仍然被困在轨道控制台上。我认为如果我在控制台中出现错误,那么继续前进是没有意义的。

按照建议,我在控制台中尝试了这个:

由于我已经有了用户,我做了user = User.find(1)book = Book.find(1)

但在下一行like = Like.create(:user => user, :book => book)上,返回了一个质量分配错误。Can't mass-assign protected attributes: book, user我想这可能会对类似模型中的attr_accessible :book_id, :user_id有所帮助,但我仍然会出错。我是不是错过了什么?

已解决

我终于开始工作了!使用CCD_ 6。

好的,这里有很多项目。我将带您进入堆栈(模型->关联->控制器>视图>>路由器(。通常,当您设计web应用程序时,您从数据库层开始,然后逐步升级。所以我们将在这里做到这一点。

型号

在这里,您可以决定需要什么数据库对象,并创建数据库表来表示它们。如果您还没有,请阅读Rails迁移指南:http://guides.rubyonrails.org/migrations.html

在您的情况下,此设置将是合适的:

class Book < ActiveRecord::Base
  attr_accessible :title
  has_many :likes
  has_many :users, through: :likes
end
class User < ActiveRecord::Base
  attr_accessible :name
  has_many :likes
  has_many :books, through: :likes
end
class Like < ActiveRecord::Base
  attr_accessible :book, :user
  belongs_to :book
  belongs_to :user
end

请注意,我们需要包含attr_accessible,这样我们就不会出现任何批量分配错误。请注意,在Rails4中,这个安全功能已经转移到控制器中。有关此方面的更多信息,请参阅或搜索inter-web:http://blog.teamtreehouse.com/rails-4-strong-paremetershttp://weblog.rubyonrails.org/2012/3/21/strong-parameters/

关联

您应该阅读有关关联的Rails指南:http://guides.rubyonrails.org/association_basics.html

这将使您了解数据库对象(活动记录对象(如何相互交互。在你的问题中,你已经设置了这些。一旦建立了关联,Rails就提供了许多用于访问它们的方法。以下是rails控制台会话的示例:rails c

# Create a user
user = User.create(:name => "Ryan") # I'm assuming User just requires a name for simplicity
  => #<User id: 1, name: "Ryan">
# Create two a books
book = Book.create(:title => "Game of Thrones")
  => #<Book id: 1, title: "Game of Thrones">
book2 = Book.create(:title => "The Well-Grounded Rubyist")
  => #<Book id: 2, title: "The Well-Grounded Rubyist">
# Create a two likes from the books and the user record
like = Like.create(:user => user, :book => book)
  => #<Like id: 1, user_id: 1, book_id: 1>
like2 = Like.create(:user => user, :book => book2)
  => #<Like id: 2, user_id: 1, book_id: 2>
# Notice how the keys glue the associations
# Query a user's likes
user.likes.count
  => 2
user.likes
  => #<ActiveRecord::Associations::CollectionProxy [#<Like id: 1, user_id: 1, book_id: 1>, #<Like id: 2, user_id: 1, book_id: 2>]
# Query a user's books
user.books
  => #<ActiveRecord::Associations::CollectionProxy [#<Book id: 1, title: "Game of Thrones">, #<Book id: 1, title: "The Well-Grounded Rubyist">]

如果有疑问,请使用导轨控制台。你会从中学到很多东西。

控制器

为了让最终用户与数据库对象进行交互,需要一个控制器来促进交换。再次阅读相关的Rails指南:http://guides.rubyonrails.org/action_controller_overview.html如果你现在还没有猜到,我强烈建议你阅读其中的大部分。

在你的事业中,我们正在创建类似的对象,所以让我们制作一个类似的控制器:

rails g controller likes index

这将创建具有索引操作和视图文件的控制器。

# app/controllers/likes_controller.rb
class LikesController < ApplicationController
  # This action will show our likes for a user.
  # Lets assume you have an authentication system (ex Devise) that logs a user in and provides a `current_user` object
  # GET /likes
  def index
    # Assign the logged in user to @user
    @user = current_user
    # Grab all of the books and put them into an array in @books
    @books = Book.all
  end
  # This is our key action. We will use this action to create a Like
  # POST /likes
  def create
    # Grab our book from the DB. Note that this syntax is for Rails 3.2 and below. Rails 4 uses something called Strong Parameters, but that is for another time. 
    book = Book.find(params[:book_id])
    # Create a like
    Like.create(:book => book, :user => current_user)
    # redirect back to the Like index page and assign a flash
    redirect_to likes_path, :notice => "You just liked the book #{book.title}" 
  end
  # here is where we will destroy a Like
  # DELETE /likes/:id
  def destroy
    # Get the like form the DB
    like = Like.find(params[:id])
    # destroy it
    like.destroy
    redirect_to likes_path, :notice => "You destroyed a like"
  end
end

路由器

路由器将外部http请求连接到控制器操作。在你的情况下,你只需要这个:

# config/routers.rb
 MyApp::Application.routes.draw do
  resources :likes
 end

这是一个Rails快捷方式,它通过相关的助手设置了7个标准路由:

    likes GET    /likes(.:format)          likes#index
          POST   /likes(.:format)          likes#create
 new_like GET    /likes/new(.:format)      likes#new
edit_like GET    /likes/:id/edit(.:format) likes#edit
     like GET    /likes/:id(.:format)      likes#show
          PUT    /likes/:id(.:format)      likes#update
          DELETE /likes/:id(.:format)      likes#destroy

帮自己一个忙,阅读本指南:http://guides.rubyonrails.org/routing.html它将解释这些路线是什么以及它们是如何工作的。Rails遵循REST,就像大多数现代web开发世界一样。

查看

在您看来,您需要一个表单供用户进行交互。此表单将数据发送到应用程序,特别是您的LikesController操作。

# app/views/likes/index.html.erb
# show your flash messages
<% flash.each do |name, msg| %>
  <div class="alert <%= "alert-#{name}" %>">
    <%= msg %>
  </div>
<% end %>
<h1>Books you may or may not like</h1>
# For each book
<% @books.each do |book| %>
  <% unless @user.books.include?(book) %> # Prob want to move this into a User instance method
    # Create a like form if the user does not have a like for this book
    <%= form_tag likes_path do %>
      <%= hidden_field_tag 'book_id', book.id %>
      # Clicking this sends a request: POST /likes with params of: book_id=123
      <%= submit_tag "Like this book", :class => "like_button" %>
    <% end %>
  <% else %>
    # Find the like. I'll admit there is probably a better way to do this but it's getting past my bed time. 
    <% like = book.likes.where(:user_id => @user.id).first %>
    # Destroy the like associated with this book and user
    <div class="unlike_button">
      # Clicking this sends a request to: DELETE /likes/123
      <%= link_to "destroy like", likes_path(like.id), :method => :delete %>
    </div>
  <% end %>
<% end %>

结论

我希望这能给你一些指导。

以后,尽量让你的问题更具体,因为这个问题涵盖了很大的领域。我刚开始积极回馈,所以我可能做得太多了。刚开始的时候,我得到了很多免费的指导和帮助。该是我回心转意的时候了。

慢慢来,当你遇到错误时,只需将其发布到谷歌即可。您可能会以"堆栈溢出"问题结束。

干杯!

相关内容

最新更新