Rails 3:尝试按照 Railscast #17 向我的帖子添加流派

发布于 2024-12-08 19:27:35 字数 697 浏览 7 评论 0原文

我完全按照 Railscast 的描述进行操作,但使用“流派”而不是“类别”,但每当我发帖时,genre_id 显示为 NULL,我收到警告:无法批量分配属性genre_ids

我的帖子模型attr_accessible中只有genre_id,因为这是属性的名称,但是什么时候我将其更改为 genre_ids。我收到错误 ActiveRecord::StatementInvalid in PostsController#create 找不到表“genres_posts”

帖子表单

<% for genre in Genre.find(:all) %>
<div>
  <%= check_box_tag "post[genre_ids][]", genre.id, @post.genre.include?(genre) %>
  <%= genre.name %>
</div>
<% end %>

帖子模型

class Post < ActiveRecord::Base

  has_and_belongs_to_many :genres

end

I've followed along exactly like the Railscast describes but using "genre" instead of "category," but whenever I make a post the genre_id shows as NULL and I'm getting a WARNING: can't mass assign attribute genre_ids

I only had genre_id in my post model attr_accessible because that's the name of the attribute, however when I change it to genre_ids. I get the error
ActiveRecord::StatementInvalid in PostsController#create Could not find table 'genres_posts'

post form

<% for genre in Genre.find(:all) %>
<div>
  <%= check_box_tag "post[genre_ids][]", genre.id, @post.genre.include?(genre) %>
  <%= genre.name %>
</div>
<% end %>

post model

class Post < ActiveRecord::Base

  has_and_belongs_to_many :genres

end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吃→可爱长大的 2024-12-15 19:27:35

我没有答案,但您应该检查以下内容:

因此,根据您之前所做的操作,您可以按照所有步骤来实现工作示例应用程序。祝你好运!

I don't have an answer, but here are the things you should check:

  • In your code, the line <%= check_box_tag "post[genre_ids][]", genre.id, @post.genre.include?(genre) %> should include genres, not genre:

    <%= check_box_tag "post[genre_ids][]", genre.id, @post.genres.include?(genre) %>

  • What Ryan Bates (I love his webcast) doesn't tell is that you need changes on your database so that your models may be stored. The reason for that is, that on a relational database, a m:n relation is normally realized by a separate table that just stores that relation only. Have a look at the "Rails Guides: Has and belongs to many associations".
  • So you have to generate a standalone migration (see the Rails Guide for that) that creates that table that hold both ids to posts and genres in one table. The table should be named therefore genres_posts, and include the columns genre_id and post_id.

So depending on what you have done before, you may follow all the steps to reach a working example application. Good luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文