我有三个模型,用户、帖子和书籍,通过第四个 kms 关联。
- 后模型有许多公里和书籍通过
- 图书模型有很多公里和帖子,通过
- km 属于 book 和 post
我已经针对上述案例尝试了本教程并且成功了。
现在,我想创建一个关联,声明一个 Post。
- 用户 has_many kms
- 公里属于用户
协会:
class User < ActiveRecord::Base
include Tenantable::Schema::Model
has_many :kms, dependent: :destroy
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me
end
class Post < ActiveRecord::Base
attr_accessible :name, :year, :author, :book_ids
has_many :kms
has_many :books, through: :kms
end
class Book < ActiveRecord::Base
attr_accessible :name
has_many :kms
has_many :posts, through: :kms
end
class Km < ActiveRecord::Base
attr_accessible :count, :book_id, :post_id, :user_id
belongs_to :book
belongs_to :post
belongs_to :user
end
这是在 PostsController 上创建的样子:
def create
#this not working
@post = current_user.build.kms(params[:post])
@post.save
end
这里的视图表单创建看起来像:
<%= form_for @post, :url => create_post_subdomain_path(@post), :method => :post do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :year, "Year" %><br />
<%= f.text_field :year %>
</div>
<div class="field">
<%= f.label :author, "Author" %><br />
<%= f.text_field :author %>
</div>
<div class="field">
<%= f.label "Book" %><br />
<%= hidden_field_tag "post[book_ids][]", nil %>
<% Book.all.each_with_index do |book, index| %>
<%= label_tag dom_id(book) do %>
<%= check_box_tag "post[book_ids][]", book.id, @post.book_ids.include?(book.id), id: dom_id(book) %> <%= book.nama %>
<% end %>
<%= '<br/><br/>'.html_safe if index == 3 %>
<% end %>
</div>
<br/>
<div class="actions">
<%= f.submit ( "Save" ), :class => "btn btn-inverse btn-medium" %> or <%= link_to 'Cancel', list_book_subdomain_path, :class => "btn btn-medium btn-primary" %>
</div>
<% end %>
我current_user.id
尝试km.user_id
在user
创建post
.
但我得到了错误
Can't mass-assign protected attributes: name, year, author, book_ids
有什么建议么?
先感谢您