使用导轨从一种形式保存到多个模型

发布于 2025-01-06 18:28:48 字数 2645 浏览 6 评论 0 原文

在过去的几周里,我一直在使用 Rails,但遇到了一个我找不到答案的问题。我觉得这可能是非常简单的事情,但它让我发疯,所以我希望得到一点指导......

我正在将数据从 1 个表单插入到 2 个模型中。一种模型称为场地,一种模型称为活动。它是一对多的关联,其中多个活动属于场馆并且场馆有许多活动。

models:

class Venue < ActiveRecord::Base
  has_many :events
  accepts_nested_attributes_for :events
end

class Event < ActiveRecord::Base
  belongs_to :venue

  scope :upcoming, where('date >= ?', Date.today)
 end  

controller:

class EventsController < ApplicationController

def new
      @venue = Venue.new
end

def create

@venue = Venue.new(params[:venue])

    if @venue.save
        render :inline => "Success"
    else
        render('new')
    end
end

end

form:

<%= form_for(@venue, :url =>{:action => 'create'}) do |f| %>

        Artist ID<br />
        <%= fields_for :event do |event_fields| %>
            <%= event_fields.text_field :artist_id %><br/><br />
        <% end %>

        Venue City<br />
        <%= f.text_field(:city) %> <br /><br />
        Venue Name<br />
        <%= f.text_field(:name) %><br/><br/>


        <div class="actions">
            <%= submit_tag "Save", :class => "btn primary" %>
        </div>

<% end %>

logoutput:

Started POST "/events" for 127.0.0.1 at 2012-02-17 19:57:24 -0500
Processing by EventsController#create as HTML
Parameters: {"utf8"=>"✓",   "authenticity_token"=>"p3llx5KsYn6gyjP9g2qwzXr+0rjh3h/o34h/iqvqjRo=", "event"=>{"artist_id"=>"124"}, "venue"=>{"city"=>" Boston", "name"=>"Bostons Fa'v"}, "commit"=>"Save"}
(0.2ms)  BEGIN
SQL (0.8ms)  INSERT INTO "venues" ("address_1", "address_2", "capacity", "city", "country", "created_at", "created_by", "name", "state", "updated_at", "url", "zip") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING "id"  [["address_1", nil], ["address_2", nil], ["capacity", nil], ["city", " Boston"], ["country", nil], ["created_at", Sat, 18 Feb 2012 00:57:24 UTC +00:00], ["created_by", nil], ["name", "Bostons Fa'v"], ["state", nil], ["updated_at", Sat, 18 Feb 2012 00:57:24 UTC +00:00], ["url", nil], ["zip", nil]]
(0.4ms)  COMMIT
Rendered inline template (0.2ms)
Completed 200 OK in 5ms (Views: 0.6ms | ActiveRecord: 1.4ms)

如您所见,它没有失败,但它只提交到 1 个模型。我的理解是,通过添加“accepts_nested_attributes_for :events”,场地模型知道然后转到我的事件表,使用我提供的事件数据创建一个新事件(在本例中只是 Artist_id),然后自动插入我的 id 字段场地表放入场地_id 中。

我在这里思考得越多,我就越觉得我可能错过了一步......如果有人有时间的话,我将不胜感激听到您对此的思考过程。

谢谢

i have been getting into rails over the course of the last couple weeks and i've run across a problem that I can not find the answer to. i feel like this is probably something really simple but it's driving me crazy so I am hoping to get a little bit a guidance...

I am inserting data from 1 form into 2 models. one model is called Venue and one model is called Events. It is a one to many association where multiple events belong to venues and venues have many events.

models:

class Venue < ActiveRecord::Base
  has_many :events
  accepts_nested_attributes_for :events
end

class Event < ActiveRecord::Base
  belongs_to :venue

  scope :upcoming, where('date >= ?', Date.today)
 end  

controller:

class EventsController < ApplicationController

def new
      @venue = Venue.new
end

def create

@venue = Venue.new(params[:venue])

    if @venue.save
        render :inline => "Success"
    else
        render('new')
    end
end

end

form:

<%= form_for(@venue, :url =>{:action => 'create'}) do |f| %>

        Artist ID<br />
        <%= fields_for :event do |event_fields| %>
            <%= event_fields.text_field :artist_id %><br/><br />
        <% end %>

        Venue City<br />
        <%= f.text_field(:city) %> <br /><br />
        Venue Name<br />
        <%= f.text_field(:name) %><br/><br/>


        <div class="actions">
            <%= submit_tag "Save", :class => "btn primary" %>
        </div>

<% end %>

log output:

Started POST "/events" for 127.0.0.1 at 2012-02-17 19:57:24 -0500
Processing by EventsController#create as HTML
Parameters: {"utf8"=>"✓",   "authenticity_token"=>"p3llx5KsYn6gyjP9g2qwzXr+0rjh3h/o34h/iqvqjRo=", "event"=>{"artist_id"=>"124"}, "venue"=>{"city"=>" Boston", "name"=>"Bostons Fa'v"}, "commit"=>"Save"}
(0.2ms)  BEGIN
SQL (0.8ms)  INSERT INTO "venues" ("address_1", "address_2", "capacity", "city", "country", "created_at", "created_by", "name", "state", "updated_at", "url", "zip") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING "id"  [["address_1", nil], ["address_2", nil], ["capacity", nil], ["city", " Boston"], ["country", nil], ["created_at", Sat, 18 Feb 2012 00:57:24 UTC +00:00], ["created_by", nil], ["name", "Bostons Fa'v"], ["state", nil], ["updated_at", Sat, 18 Feb 2012 00:57:24 UTC +00:00], ["url", nil], ["zip", nil]]
(0.4ms)  COMMIT
Rendered inline template (0.2ms)
Completed 200 OK in 5ms (Views: 0.6ms | ActiveRecord: 1.4ms)

As you can see its not failing but it is only submitting to the 1 model. My understand is that by adding "accepts_nested_attributes_for :events" the Venue model knows to then go to my Events table, create a new event with the event data I provide (in this example just artist_id), and then automatically insert the id field from my venue table into venue_id.

The more I think about this here the more I think I might be missing a step and....If anyone has a second I would appreciate hearing your thought process on this.

Thanks

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

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

发布评论

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

评论(2

腻橙味 2025-01-13 18:28:48

我认为您的表单中有语法错误。 fields_for 是 f 的一种方法,它需要一个复数符号。将块的迭代器设置为单数也是一种很好的做法,当您的方法只需要一个参数时,不要使用括号:

<%= form_for(@venue, :url =>{:action => 'create'}) do |f| %>

        Artist ID<br />
        <%= f.fields_for :events do |event_field| %>
            <%= event_field.text_field :artist_id %><br/><br />
        <% end %>

        Venue City<br />
        <%= f.text_field :city %> <br /><br />
        Venue Name<br />
        <%= f.text_field :name %><br/><br/>


        <div class="actions">
            <%= submit_tag "Save", :class => "btn primary" %>
        </div>

<% end %>

请参阅 Ryan Bate 的 Railscasts

<%= form_for @survey do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <% f.fields_for :questions do |builder| %>
  <p>
    <%= builder.label :content, "Question" %><br />
    <%= builder.text_area :content, :rows => 3 %>
  </p>
  <% end %>
  <p><%= f.submit "Submit" %></p>
<% end %>

I think you have a syntax error in the form. The fields_for is a method of f and it expects a plural symbol. It is also a good practice to have the iterator of a block in singular, and not to use parentheses when your method only expects one parameter:

<%= form_for(@venue, :url =>{:action => 'create'}) do |f| %>

        Artist ID<br />
        <%= f.fields_for :events do |event_field| %>
            <%= event_field.text_field :artist_id %><br/><br />
        <% end %>

        Venue City<br />
        <%= f.text_field :city %> <br /><br />
        Venue Name<br />
        <%= f.text_field :name %><br/><br/>


        <div class="actions">
            <%= submit_tag "Save", :class => "btn primary" %>
        </div>

<% end %>

See this example of a nested form in Ryan Bate's Railscasts:

<%= form_for @survey do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <% f.fields_for :questions do |builder| %>
  <p>
    <%= builder.label :content, "Question" %><br />
    <%= builder.text_area :content, :rows => 3 %>
  </p>
  <% end %>
  <p><%= f.submit "Submit" %></p>
<% end %>
心欲静而疯不止 2025-01-13 18:28:48

Venue 模型需要指定哪些属性是可批量分配的,包括 Event 属性。

attr_accessible :event_attributes, :address_1, :address_2, :capacity # ...

Venue model needs to specify which attributes are mass-assignable, including Event attributes.

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