簡體   English   中英

Rails-一個視圖中有2個模型(屬於屬於另一個模型的模型)

[英]Rails - 2 models in one view (of model that belongs_to another)

對此有幾個問題和答案,除了每次模型視圖使用與我需要的相反時。 就我而言,我要在一個視圖中顯示3個模型。 Post belongs_to UsernameUsername has_many Posts 我擁有的第三個模型是Category has_many Posts ,它通過集合選擇正確顯示。 該視圖是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 %>

那就是我想要做的-顯示username.name(在帖子中我有FK username_id)。 上面的代碼fields_for不起作用,它什么也不顯示。 我發現的關於該問題的所有答案都在has_many模型的視圖中,而我在belongs_to模型的視圖中則需要它。 那么,如何在帖子視圖中訪問具有has_many個帖子的用戶名模型的名稱屬性? (到目前為止,我只能訪問Post模型中的外鍵)。

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

class Username < ActiveRecord::Base
  attr_accessible :name
  has_many :posts
  validates :name, :presence => true
end

routes.rb

resources :usernames
resources :categories
resources :posts

請幫忙!

accepts_nested_attributes_for :username  

在您的post.rb中

但是您不希望帖子自動分配給current_user嗎????

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM