【发布时间】:2013-04-11 11:38:25
【问题描述】:
我有三个模型,用户、帖子和书籍,通过第四个模型 kms 关联。
- 后模型有许多公里和书籍通过
- 图书模型有许多公里和帖子通过
- km 属于书帖
上述案例我试过this tutorial,成功了。
现在,我想创建一个关联来声明一个帖子。
- 用户有_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 %>
当user 创建post 时,我尝试生成current_user.id 到km.user_id。
但我得到了错误
Can't mass-assign protected attributes: name, year, author, book_ids
有什么建议吗?
提前谢谢你
【问题讨论】:
-
你的问题到底是什么?
-
您的意图目前还不清楚。你想做什么?请重写你想要发生的事情。其余的都是有道理的。
-
当
user创建post时,我尝试生成current_user到km,但不工作,我收到错误Can't mass-assign protected attributes: name, year, author, book_ids
标签: ruby-on-rails ruby-on-rails-3.2 model-associations