【发布时间】:2023-03-13 20:28:01
【问题描述】:
我正在尝试以作者身份填充 user_id 参数。我想要做的基本上是,如果您是具有角色作者的登录用户并且您创建了一本书,我希望它使用您的登录 ID 来填充该 user_id 参数,如果您以管理员用户身份登录,您可以创建一个书,但使用选择的用户/作者列表添加到书。
这是我得到的:
图书控制器
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 %>
我想要做的就是让作者使用他们的登录数据创建/更新书籍以填充参数 user_id 并让管理员通过使用下拉列表而不是填充参数 user_id 来创建/更新书籍。
【问题讨论】:
-
你的问题是什么,什么不起作用?
-
它没有填充 user_id 参数
-
我希望
params[:book][:user_id]中的user_id不仅仅是params[:user_id]。 -
是的,我也试过了,但它仍然没有填充它。
标签: ruby-on-rails ruby ruby-on-rails-4 devise cancan