如何在Rails中使用simple_form访问嵌套资源的编辑方法?

时间:2018-07-22 15:48:37

标签: ruby-on-rails simple-form nested-resources

我有3个模型:BookUserBookUser(来自设计)。 UserBook通过UserBookhas_many:users through: :user_books链接。

我一直在尝试使用user_books中的简单形式访问books#show中的edit和destroy方法,以将布尔值have_or_wantfalse更改为{{ 1}}。这些是模型:

true

想法是,您可以在class Book < ApplicationRecord has_many :user_books has_many :users, through: :user_books validates :title, :author, presence: true validates :rating, inclusion: {in: [1,2,3,4,5], allow_nill: false } end class UserBook < ApplicationRecord belongs_to :user belongs_to :book end class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :user_books has_many :books, through: :user_books end 中看书,而if语句决定显示三个books#show中的哪个:

如果没有simple_formsUserBook链接到书,则将有一个单选按钮,如果您要将其添加到自己的书集(current_user)中或将其添加到您的阅读清单(@user_book.have_or_want: true)。这个工作正常,并且使用@user_book.have_or_want: false正确创建了一个新的UserBook

我现在正在尝试提供一种表格,用于当用户在阅读user_books#update的书时,提供将书标记为已读的选项(用{{将list(@user_book.have_or_want)更改为@user_book.have_or_want 1}})或删除图书(true)。

还有第三种形式,用于通过删除user_books#update来删除书集(user_books#destroy)。

在路由中,@user_book.have_or_want: true嵌套在@user_book中。

UserBook中的if语句和简单形式如下所示,并且第一部分起作用。

Book

我尝试了几种方法来完成第二部分,这是我目前的最佳猜测。我得到的错误是:

books#show

<% if current_user.books.exclude? @book %> <%= simple_form_for [@book, @user_book] do |f| %> <%= f.input :have_or_want, :collection => [[true, 'Add to Bookshelf'], [false, 'Add to resding list']], :label_method => :last, :value_method => :first, :as => :radio_buttons %> <%= f.submit "Submit" %> <% end %> <% elsif @book.user_books[0].have_or_want == false %> <!-- If is is on the reading list you can add to bookshelf(changes have_or_want to true) or can remove from reading list (delete user_book instance) --> <%= simple_form_for [@book, @user_book], url: book_user_book_path(@book, @user_book), method: :patch do |f| %> <%= f.input :have_or_want %> <%= f.submit "Submit" %> <% end %> <% else %> <!-- It is on the bookshelf so option to remove - user_books#destroy? --> <% end %> 也是No route matches {:action=>"show", :book_id=>"1", :controller=>"user_books", :id=>nil}, missing required keys: [:id] ,所有值为nil。

0 个答案:

没有答案