gpt4 book ai didi

mysql - Ruby on Rails - 隐藏标签不传递到数据库

转载 作者:行者123 更新时间:2023-11-29 03:26:36 25 4
gpt4 key购买 nike

RoR 的新手,遇到了一个我无法在任何地方找到答案的问题。

我有两个表,userbooks,我正在尝试使用连接表来匹配用户和书籍并添加评级和评论连接表中的列。问题是除了 book_id

之外的所有内容都传递到连接表中

查看

<%= form_for(current_user.user_book_collections.build) do |f| %>
<div>
<%= hidden_field_tag :book_id, current_book.id %>
<%= f.label :rating %>
<%= f.text_field :rating, class:"form-control" %>
<%= f.label :review %> (optional):
<%= f.text_area :review, size: "24x8", placeholder: "Please enter a brief review... ", class:"form-control" %>
</div>
<p></p>
<%= f.submit "Add to your collection", class:"btn btn-primary" %>
<% end %>

current_usercurrent_book 是分别分配用户和书籍的方法。

Controller

def create
@user_book_collection = current_user.user_book_collections.build(user_book_collection_params)
if @user_book_collection.save
flash[:success] = "Added to your collection"
redirect_to mybooks_path
else
flash[:danger] = "Add was unsuccessful"
redirect_to bookcollection_path
end
end

private

def user_book_collection_params
params.require(:user_book_collection).permit( :book_id, :user_id, :review, :rating )
end
end

这是控制台中显示的内容:

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"85gmzUO7ldQrevh/qnKwYO9mkd9lX77sG3xxJQV8Y46xZrkl5ifk665abPr79nOT91rO3oLcMSDgYL7BtR+/XQ==", "book_id"=>"6", "user_book_collection"=>{"rating"=>"s", "review"=>"asd"}, "commit"=>"Add to your collection"}

但随后也在控制台中检查记录,我可以看到 book_id 没有通过,即使它已在参数中分配:

=> #<ActiveRecord::Associations::CollectionProxy [#<UserBookCollection id: 10, user_id: 7, book_id: nil, review: "asd", rating: "s", created_at: "2016-02-07 06:36:33", updated_at: "2016-02-07 06:36:33">

如有任何帮助,我们将不胜感激。

最佳答案

这是因为您的表单的构建方式是 book_idparams[:book_id] 中传递,而不是在 params[:user_book_collection][: book_id] 因此不存在于 user_book_collection_params

使用:

f.hidden_field :book_id, value: current_book.id

关于mysql - Ruby on Rails - 隐藏标签不传递到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35252427/

25 4 0