Ruby on rails 如何定义已通过的参数?
我在人际关系中使用has_很多,我真的不知道我应该做些什么才能让它起作用。 我想有一些关于参数的东西我不理解,并且忽略了。如果是这样,请告诉我在哪里以及如何写,因为我有点困惑,因为所有这些参数。 book.rb: user.rb:Ruby on rails 如何定义已通过的参数?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我在人际关系中使用has_很多,我真的不知道我应该做些什么才能让它起作用。 我想有一些关于参数的东西我不理解,并且忽略了。如果是这样,请告诉我在哪里以及如何写,因为我有点困惑,因为所有这些参数。 book.rb: user.rb: class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
validates :full_name, presence: true
has_many :user_books
has_many :books, through: :user_books #books_users - book_id user_id
end
和books_controller.rb:
class BooksController < ApplicationController
before_action :is_admin?, except: [:show_my_books, :book_params]
before_filter :authenticate_user!
expose(:book, attributes: :book_params)
expose(:user_book)
expose(:user_books)
expose(:books){current_user.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 show
end
def is_admin?
if current_user.admin?
true
else
render :text => 'Who are you to doing this? :)'
end
end
def book_params
params.require(:book).permit(:name, :author, :anotation, user:[:name])
end
end
当我写新书时,它给了我一个错误
找不到“id”=27[其中用户\u books.user\u id=?]的书籍
很抱歉问了一个愚蠢的问题,但我自己找不到一个合适的例子来理解它,这就是为什么我请求你的帮助。非常感谢您的帮助,谢谢 要通过表单设置关系,通常使用选择或复选框并传递相关项目的ID: 对于一对一关系,请求如下所示:
POST /books { book: { name: 'Siddharta', author: 'Herman Hesse', user_id: 1 } }
对于多对多或一对多,您可以使用_id:
ActiveRecord为has\u many和HABTM关系创建一个特殊关系\u name\u ids=setter和getter。它允许您通过传递ID数组来修改对象的关系
您可以这样创建表单输入:
<%= form_for(@book) do |f| %>
<%= f.collection_select(:author_ids, User.all, :id, :name, multiple: true) %>
OR
<%= f.collection_checkboxes(:author_ids, User.all, :id, :name) %>
<% end %>
另一方面,如果要将记录分配给当前用户,最好从会话或令牌中获取用户,并避免传递参数:
def create
@book = current_user.books.new(book_params)
# ...
end
这样可以避免恶意用户传递另一个用户id或通过传递自己的id控制资源的非常简单的黑客行为
至于您的另一个错误,为什么它会尝试创建一个奇怪的查询,需要某种堆栈跟踪或日志
然而,如果你是Rails的新手,你可能想推迟一点关于曝光率的讨论。它模糊了魔法中的许多重要概念,你会花更多的时间去弄清楚它是如何工作的,而花更多的时间去学习如何构建好rails应用程序可能会更好。我正在使用Delegate_exposure gem来缩短控制器,当它崩溃时你想做什么?@Max Emm。。。如果我正确理解了您的问题,当我遇到此错误时,我尝试添加新方法def user_book_params,其中包含params.require:user_book.permit:user_id,:book_id,但它仍然不起作用,而且我不确定在book_controllerI中定义其他模型的参数是否正确。我的意思是,你在做什么来触发错误-例如,单击链接或提交表单。正在调用哪个操作?错误在哪一行?如果你能对你正在尝试做的事情给出一个高层次的描述,etcI将非常有帮助——用户应该能够创建一本书,并且它应该与该用户关联,或者用户应该能够。。。。你已经建立了关系,但你没有告诉我们你打算如何使用它。
<%= form_for(@book) do |f| %>
<%= f.collection_select(:author_ids, User.all, :id, :name, multiple: true) %>
OR
<%= f.collection_checkboxes(:author_ids, User.all, :id, :name) %>
<% end %>
def book_params
params.require(:book).permit(:name, :author, :anotation, user_ids: [])
end
def create
@book = current_user.books.new(book_params)
# ...
end