如何使用链接将数据发送到没有GET方法的另一个控制器?

时间:2019-01-07 10:12:37

标签: ruby-on-rails-5

我正在使用Rails 5.2.2。我有'GET /': { view: 'cn/homepage' }usersauthors表。每个用户只能看到自己保存的记录。

Books表具有booksuser_id外键。我需要自动保存该数据。

在我的author_id文件中,我创建了一个books_controller.rb方法来自动添加此数据,例如,

set_defaults

def set_defaults params[:book][:user_id] = current_user.id end 没问题,但是我不知道如何访问作者ID。

我在user_id页下添加了一个链接,并希望使用该链接向作者添加图书。

那么我如何以安全的方式获取author_id?

authors#show

这将重定向到<a href="<%= new_author_book_path(@author) %>" class="btn btn-block btn-info" style="color: white">Add a Book</a>

我不想使用链接中的ID,也不想使用get方法。 我只想使用链接(添加一本书)来保存一本书。那么如何将那个作者对象传递给控制器​​?

2 个答案:

答案 0 :(得分:1)

以您的html格式:

<%= form_for [@author, @book] do |f| %>
  # Your Book fields here
<% end %>

在您的控制器中(没有授权gem)

class AuthorsController < ApplicationController
  def show
    @author = current_user.authors.find(params[:id])
  end

  def create 
    @author = current_user.authors.find(params[:id])
    @book = Book.new(book_params)
    if @book.save
      # handle save 
    else
      # handle error
    end
  end 

  private 

  def book_params
    params.require(:book).permit(:title .....)  
  end
end

答案 1 :(得分:0)

好的,我找到了解决方案,但是我不确定这是一个好习惯。任何更好的解决方案将不胜感激。

我在作者show.html.erb页面中创建了一个全局变量:

$current_author = @author

我在books_controller.rb

中使用了它
params[:book][:author_id] = $current_author.id