Javascript: Using a method from model in javascript code

╄→гoц情女王★ 提交于 2020-01-07 05:09:10

问题


I am trying to set up users on an asset, and I am running into the problem of not being sure how to pass my max_users method from asset.rb to my JS code. I am trying to use the max_users method with the Cocoon gem to have the "Add Another" button disappears when it reached the specified max_users allowed for that asset.

Hardware will always be set with a max_user of 1, while software will never have a max_user value.

Max_users works as it should, as does profile_type. The JS works as it is, but instead of it always stopping at 1, I need to have it register the value in max_users, and base the show/hide off of that.

Any help will be much appreciated. And thank you in advance.

JS:

$ ->
  check_to_hide_add_link = ->
    if $("#assets_users .nested-fields").length is 1
      $("#assets_users .links a").hide()
    else
      $("#assets_users .links a").show()

  $("#assets_users").bind "cocoon:after-insert", ->
    check_to_hide_add_link()

  $("#assets_users").bind "cocoon:after-remove", ->
    check_to_hide_add_link()

  check_to_hide_add_link()

Asset.show:

- if @asset.users.empty?
    = simple_form_for([@asset_profile, @asset]) do |f|
      = f.input :max_users, as: :hidden
      #assets_users
        = f.simple_fields_for :assets_users do |assets_user|
          = render "assets_user_fields", f: assets_user
        .links
          = link_to_add_association "Add Another User", f, :assets_users
        = f.submit

_assets_user_fields:

.nested-fields
  = f.input :user_id, collection: @users.order(:last_name), :label => "User"
  = link_to_remove_association "Remove", f

Asset.rb:

def max_users
  if self.asset_profile.profile_type == "Hardware"
    1
  end
end
.
.
.
def length_of_users
  if user_ids.count > max_users
    errors.add(:users, "You can only add a maximum of #{max_users} users")
  end
end

回答1:


Had to retrieve the value of max_users, and convert it into an integer. Then just plugged it in so that if the amount of fields showing up was greater than, or equal to, the max_users, the form would stop generating new fields.

$ ->
  check_to_hide_add_link = ->
    max_users = parseInt($("#asset_max_users").val(), 10)
    if $("#assets_users .nested-fields").length >= max_users
      $("#assets_users .links a").hide()
    else
      $("#assets_users .links a").show()

  $("#assets_users").bind "cocoon:after-insert", ->
    check_to_hide_add_link()

  $("#assets_users").bind "cocoon:after-remove", ->
    check_to_hide_add_link()

  check_to_hide_add_link()


来源:https://stackoverflow.com/questions/26743374/javascript-using-a-method-from-model-in-javascript-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!