0

I have a Class Foo has many Bar(s)

I have a form which contains the nested class Bar and when the form submits I would like Bar that was built to have an IP address associated to it from the server. My issue is I do not know how to call a method through params to set the IP in Bar when Foo is created

In the Foo controller

def new
 @foo = Foo.new
 @foo.bars.build
end

def create
  @foo.Foo.create(params[:foo])
  if @foo save 
     #error code
     #b = Bar.find(params[:bar_id])
     # b.setIP request.remote_ip
  end
end

Form

<%= form_for @foo do |f| %>
    <%= f.label "Comment : " %>
    <%= f.fields_for :bars do |comment_form| %>
        <%= comment_form.text_area :comment %>
        <%= f.label "Terms of Service" %>
        <%= comment_form.check_box :terms %>

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

<% end %>
4

1 回答 1

1

你能试试这个吗?

def create
  @foo = Foo.new(params[:foo])
  @foo.bars[0] = request.remote_ip
  if @foo save 
     #it's ok
  end
end

说明:当您有嵌套属性时,您创建 Foo 和一个或多个 Bars(一对多关系)。在您的情况下,您只制作了一个 Bar,但这并不会改变您拥有一对多关系的事实,您在 bar 中只有一个元素。因此,您将 bar[0] 用于访问 bar 数组 (ActiveRecord::Relation) 的第一个也是唯一一个元素。

于 2013-06-19T00:31:58.427 回答