Search code examples
ruby-on-railsrubylink-to

How to call a method from controller using link_to?


I want my app to add a book to current_user when he clicks the link. My code seems to be ok, there are no errors but after user clicks the link nothing happens.

book.rb:

has_many :book_users
has_many :users, through: :book_users

user.rb:

has_many :book_users
has_many :books, through: :book_users

book_user.rb:

belongs_to :book
belongs_to :user

books_controller.rb:

before_action :is_admin?, except: [:book_params, :add_to_books_i_read, :index]
before_filter :authenticate_user!
expose(:book, attributes: :book_params)
expose(:books)


  def create
    if book.save
      redirect_to(book)
    else
      render :new
    end
  end

  def update
    if book.save
      redirect_to(book)
    else
      render :edit
    end
  end

  def add_to_books_i_read(book_id)
    current_user.books << Book.find(book_id)
  end

In my index view I have

ul
  -books.each do |book|
    li
      = link_to "#{book.name}", book_path(book)
      = link_to "  Add to my books", {:controller => "books", method: :add_to_books_i_read, book_id: :book.id}

So, what am I doing wrong? Why my method add_to_books_i_read does nothing? The table in database book_users doesn't record anything after clicking this link_to, but it works well itself (I checked via console). What can I do? How to make users add books through the method and how to call this method correctly? Every help would be appreciated, thank you!


Solution

  • Oh God. With your advise help I've finally got it! So,

    Controller:

    def add_to_books_i_read
        current_user.books << Book.find(params[:id])
        redirect_to(:back) #this line
    end
    

    In routes

    resources :books do
        member do
          get :add_to_books_i_read
        end
    end
    

    index view

    -books.each do |book|
        li
          = link_to "#{book.name}", book_path(book)
          = link_to  "       Add to my books", add_to_books_i_read_book_path(book)
    

    Thank you all for your help! I'm really really grateful! :)