我正在尝试将user_id param填充为Author。我想要做的基本上是如果你是一个有角色作者的登录用户并且你创建了一本书我希望它使用你登录的id来填充那个user_id param,如果你以管理员用户身份登录就可以创建一个预订,但使用选择的用户/作者列表添加到书中。
这是我所拥有的:
BooksController中
def create
# raise params.inspect
@book = Book.create(book_params)
if current_user.role_id == '2'
@book.user_id = current_user.id
else
@book.user_id = params[:user_id]
end
#binding.pry
respond_to do |format|
if @book.save
format.html { redirect_to @book, notice: 'Book was successfully created.' }
format.json { render action: 'show', status: :created, location: @book }
else
format.html { render action: 'new' }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
def update
@book.user_id = current_user.id
respond_to do |format|
if @book.update(book_params)
format.html { redirect_to @book, notice: 'Book was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
然后在我的表单视图中我有这个设置:
<% if current_user.role.name == "Author" %>
<div id="author" class="field">
<!-- <h3>Hey <%= current_user.name %> your signed in as an <%= current_user.role.name %></h3> -->
</div>
<% elsif %>
<div id="author" class="field">
<h3>Select author of book</h3>
<%#= debug Book.book_authors %>
<%= f.collection_select :user_id, User.order(:name),:id,:name, {:include_blank => false} %>
</div>
<% end %>
我想要做的就是让作者使用他们登录的数据创建/更新书籍,以填充param user_id和管理员以使用下拉列表来创建/更新书籍,而不是填充param user_id。
答案 0 :(得分:0)
你想要立刻做太多事。简化问题并获得小工作。例如,您在更新控制器中使用@book而不首先定义它。作为另一个示例,您在create controller中引用role_id(int)。您的表单引用role.name(字符串)。
首先使控制器工作,然后添加您的功能。
答案 1 :(得分:0)
可能的问题/解决方案:
1)
if current_user.role_id == '2'
我假设你有一个角色模型和一个用户has_one:角色关联。如果是这种情况,你不应该使用'2'而是2不使用单引号。 foreign_key不是字符串而是整数。如果你没有这样的模型/关联,那么你以后就不能使用user.role.name了。
2)当您使用Book.create(book_params)时,您不仅要实现一本书,而且将其保存(如果有效)到DB。你可以创建一个没有user_id的书吗?如果没有,那么你就错了,因为你在分配作者之前试图创建那本书(当作者填写表格时,她在提交时没有传递user_id)。
3)主要嫌疑人是你的book_params。检查服务器日志以查看您是否正在传递user_id参数,但它被阻止为未经许可。检查您是否包括:user_id in yourrs params .... permit(:user_id)
其他评论:
a)我建议你替换Book.create for Book.new。但是如果你保留book.create,则不需要以下内容:
...
else
@book.user_id = params[:user_id]
end
(你已经用这个用户ID创建了这本书。它也应该是params [:book] [:user_id]
b)正如Matt所说,如果你没有在更新中设置带有before_action的@book,那么你还有另一个问题。