UJS,AJAX,Rails 4,form_for collection_select将值传递给方法并将值返回给表单

UJS,AJAX,Rails 4,form_for collection_select将值传递给方法并将值返回给表单

问题描述:

我对Rails还是很陌生,因此在一起处理AJAX,UJS和Rails时会产生很多困惑.我看过railscast,有几个答案,在freenode上尝试了#rubyonrails IRC频道. las,我仍然被困住.

I'm very new to Rails, and as such am having lots of of confusion when dealing with AJAX, UJS and Rails together. I've looked at railscast, several SO answers, tried #rubyonrails IRC channel on freenode. Alas, I'm still stuck.

反正这是我的问题.

因此,我有两个模型,即建筑模型和属性模型.财产属于建筑物,建筑物具有has_many属性.

SO I have two Models, Building and Property. Property belongs_to Building and Building has_many Properties.

我已将外键添加为Property作为building_id.

I've added the foreign key to Property as building_id.

现在,在我的建筑模型中,我有一个方法:self.search(search)并指定了正确的地址(例如999 Decarie),它将正确地从数据库中的Building表返回building_id.

Now, in my building model, I have a Method: self.search(search) and given the right address (example 999 Decarie), it will return the building_id from Building table in the database correctly.

def self.search(search)
    #search.instance_variables.map {|v| "#{v}: #{search.instance_variable_get(v)}\n"}.join
    if ((search.nil?) || (search == ""))
        nil
    else
        search = search.to_s
        d { search }
        split = search.split(' ', 2)
        stnum = split.first
        d { stnum }
        stname = split.last
        d { stname }
        Building.where("streetno = ?", stnum).where("streetname = ?", stname).pluck(:id).first
    end
end

在我的Properties局部_form中,我有一个form_for循环,该循环使用collection_select来允许用户选择任何建筑物地址(例如999 Decarie),(因此它呈现为选择/选项HTML下拉列表).

In my Properties partial _form, I have a form_for loop that uses a collection_select to allow the users to pick any building address (ex. 999 Decarie), (so it renders as a select/option HTML drop-down list).

<div class="field" id="selection">
   <%= f.collection_select :buildinginfo, Building.all, :half_address, :half_address, {:label => "Building Info"}%>
</div>  

那么,如何使用不引人注目的javascript/ajax

So, how do I, using unobtrusive javascript/ajax

A.用户在表单中选择集合后,立即获取所选集合的选定值,并将其传递给上述的建筑物模型方法(self.search(search)),该方法将返回正确的建筑物ID.

A. Get the selected value of the collection select as soon as the user selects it in the form and pass it to the building model method mentioned above (self.search(search)), which returns the correct building ID.

B.立即获取该方法返回的建筑物ID,并将其存储在表单的隐藏字段中(与属性"模型中的building_id字段相对应). (在下面的代码中,我想用建筑物ID替换值1)

B. immediately take the building ID returned by the method and store it in a hidden field on the form (which corresponds to building_id field in the Properties model). (in the code below I want replace the value 1 with the building ID)

 <div class="field" id="selection_id">
         <%= f.hidden_field :building_id, :value => 1 %>  
      </div>    

因此,允许我的关联正常工作,以便在删除建筑物时,其所有相关属性也将被删除.

Thus, allowing my associations to work such that when I delete a building, all its related properties get deleted as well.

让我知道您是否需要更多代码,我正在使用Rails 4,非常感谢!

Let me know if you need more code, im using Rails 4, thank you so much!

感谢您抽出宝贵的时间来解释此Rich.

thanks for taking the time to explain this Rich.

虽然您的方法有意义,但是我使用了另一种方法,因为我的最终目标只是在Building(has_many)和Property(belongs_to)之间创建关联,并且当我删除Building时,我还希望删除与之关联的所有Properties也是

While your approach makes sense, I used a different approach, because my end goal was simply to create associations between Building (has_many) and Property (belongs_to), and when I delete a Building I also want all Properties associated to it deleted as well.

因此,在创建/更新属性时,我需要将其添加到Building.properties数组中,该数组会自动更新属性的building_id字段.

So when creating/updating a property I need to add it to the Building.properties array, which automatically updates the property's building_id field.

这是我在properties_controller中的最终代码:

here's my final code in the properties_controller:

def create
  @property = Property.new(property_params)

  **b_id = Building.search(@property.buildinginfo)**
  **Building.find_by(id: b_id).properties << @property**

  respond_to do |format|
    if @property.save
      format.html { redirect_to @property, notice: 'Property was successfully created.' }
      format.json { render :show, status: :created, location: @property }
    else
      format.html { render :new }
      format.json { render json: @property.errors, status: :unprocessable_entity }
    end
  end
end

def update
respond_to do |format|
  if @property.update(property_params)

    **b_id = Building.search(@property.buildinginfo)**
    **Building.find_by(id: b_id).properties << @property**

    format.html { redirect_to @property, notice: 'Property was successfully updated.' }
    format.json { render :show, status: :ok, location: @property }
  else
    format.html { render :edit }
    format.json { render json: @property.errors, status: :unprocessable_entity }
  end
end
end

Building.search函数(在Building Model中):

The Building.search function (goes in the building Model):

    def self.search(search)

    if ((search.nil?) || (search == ""))
        nil
    else
        search = search.to_s
        split = search.split(' ', 2)
        stnum = split.first
        stname = split.last
        s = Building.where("streetno = ?", stnum).where("streetname = ?",  stname).pluck(:id).first
        s
    end
end