[英]Rails - 2 models in one view (of model that belongs_to another)
There were several questions and answers for this, except that every time the model view used the opposite of what I need. 对此有几个问题和答案,除了每次模型视图使用与我需要的相反时。 In my case, I have 3 models that I want to display in one View.
就我而言,我要在一个视图中显示3个模型。
Post belongs_to Username
, Username has_many Posts
. Post belongs_to Username
, Username has_many Posts
。 The third model I have is Category has_many Posts
, which displays correctly through collection select. 我拥有的第三个模型是
Category has_many Posts
,它通过集合选择正确显示。 The view is of Post model, _form.html.erb 该视图是Post模型_form.html.erb
<%= form_for(@post) do |f| %>
<%= f.label :equipment %><br />
<%= f.text_field :equipment %><br />
<%= f.label 'Serial number' %><br />
<%= f.text_field :serial_num %><br />
<%= f.label :category %><br />
<%= collection_select(:post, :category_id, Category.all, :id, :name, prompt: true) %>
<%= f.fields_for :usernames do |user| %>
<%= user.label :username %><br />
<%= user.text_field :name %>
<% end %>
<% end %>
That is what I want to do - to display username.name (in post I have FK username_id). 那就是我想要做的-显示username.name(在帖子中我有FK username_id)。 The above code
fields_for
doesn't work, it displays nothing. 上面的代码
fields_for
不起作用,它什么也不显示。 All the answers on this question that I found are in the view of has_many
model, while I need this in the view of belongs_to
model. 我发现的关于该问题的所有答案都在
has_many
模型的视图中,而我在belongs_to
模型的视图中则需要它。 So, how can I access name attribute of Username model that has_many Posts in post view? 那么,如何在帖子视图中访问具有has_many个帖子的用户名模型的名称属性? (So far I can only access foreign key, which is in Post model).
(到目前为止,我只能访问Post模型中的外键)。
post.rb post.rb
class Post < ActiveRecord::Base
attr_accessible :category_id, :equipment, :serial_num, :username_id
belongs_to :category
belongs_to :username
validates :username_id, :presence => true
end
username.rb username.rb
class Username < ActiveRecord::Base
attr_accessible :name
has_many :posts
validates :name, :presence => true
end
routes.rb routes.rb
resources :usernames
resources :categories
resources :posts
Please help! 请帮忙!
accepts_nested_attributes_for :username
in your post.rb 在您的post.rb中
But don't you want the post to automatically be assigned to the current_user????? 但是您不希望帖子自动分配给current_user吗????
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.