简体   繁体   English

Rails如何从关联的模型中添加记录新页面

[英]Rails how to add record from an associated models new page

I have 2 models setup like so: 我有2种型号设置,如下所示:

class Campaign < ApplicationRecord
  has_many :cities
  belongs_to :user
end

class City < ApplicationRecord
  belongs_to :campaign
end

Controller: 控制器:

  def new
    @campaign = current_user.campaigns.build
    @cities = @campaign.cities
  end

I would like users to be able to create and edit cities directly from the campaign page. 我希望用户能够直接从广告系列页面创建和编辑城市。 I am not sure how to do this, here is my attempt. 我不确定如何执行此操作,这是我的尝试。 How do I access city.name? 如何访问city.name? :name is the param key for @campaign :name是@campaign的参数键

<%= form_for @campaign do |f| %>
  <%= f.label "Name" %>
  <br />
  <%= f.text_field :name %>
  <br /> <br />

  <%= f.label "Titles" %>
  <br />
  <%= f.text_area :titles, cols: 80, rows: 20 %>
  <br /> <br />

  <%= f.label "Sentences" %>
  <br />
  <%= f.text_area :sentences, cols: 80, rows: 20 %>
  <br /> <br />

  <%= f.label "Keywords" %>
  <br />
  <%= f.text_area :keywords, cols: 80, rows: 20 %>
  <br /> <br />

  <% if @cities.count > 0 %>
    <h2>Cities</h2>
    <% for city in @cities %>
      <%= f.label "City name:" %>
      <br />
      <%= f.text_area :name, cols: 80, rows: 20 %>
    <% end %>
  <% end %>

  <%= f.submit "Submit" %>
<% end %>

I was able to do this with: 我能够做到这一点:

   <% if @cities.count > 0 %>
    <h2>Cities</h2>
    <% for city in @cities %>
      <%= form_for city do |f| %>
        <%= f.text_area :name, cols: 20, rows: 1 %>
        <%= f.text_area :phone_number, cols: 20, rows: 1 %>
        <%= f.text_area :zip_code, cols: 20, rows: 1 %><%= f.submit "Submit" %>
      <% end %>
    <% end %>
  <% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM