how to add a related field many2one? - field

I have a field on stock_picking table I would like to relate it with stock_move
_inherit= 'stock.picking'
_columns={
'user_id': fields.many2one('res.users', 'user', select=True),
}
I would like to relate the field user_id with stock_move
I tried this
_inherit= 'stock.move'
_columns={
'user_id': fields.related('picking_id', 'user_id', relation="res.users", type='many2one', string="user", store=True, readonly=True)
}
any Idea brothers?

You have used wrong model in inherit it should be as follows:
_inherit= 'stock.picking'
_columns={
'user_id': fields.many2one('res.users', 'user', select=True),
}
_inherit= 'stock.move'
_columns={
'user_id': fields.related('picking_id', 'user_id', relation="res.users", type='many2one', string="user", store=True, readonly=True)
}

Agree with #Hardik Patadia. But you may also try with type=char
_inherit= 'stock.picking'
_columns={
'user_id': fields.many2one('res.users', 'user', select=True),
}
_inherit= 'stock.picking.in'
_columns={
'user_id': fields.many2one('res.users', 'user', select=True),
}
_inherit= 'stock.picking.out'
_columns={
'user_id': fields.many2one('res.users', 'user', select=True),
}
_inherit= 'stock.move'
_columns={
'user_id': fields.related('picking_id', 'user_id', 'name', type='char', string='User', store=True, readonly=True ),
}
Here is an example

Related

Unable to split the statement into multiple lines from an array in Ruby

I want to split the statement array into 2 different lines in RUBY:
statement = ["Statement1", "Statement2"]
This is how I am splitting the array
result = statement.split(", ")
The output what I want is:
Statement1
Statement2
But I am getting the error as:
undefined method `split' for ["Statement1", "Statement2"]:Array (NoMethodError)
Can someone please help me?
Thanks in advance
You can iterate over the array.
stmtAry = ["Statement1", "Statement2"]
stmtAry.each{|i| puts i}
You can directly output each statement without iterating on them if you don't need any other operation other than printing out.
stmtAry = ["Statement1", "Statement2"]
puts stmtAry
Both codes provides the same output:
Output:
Statement1
Statement2
It doesn't go much shorter :
puts statement
# Statement1
# Statement2
From the puts documentation :
If called with an array argument, writes each element on a new line.
If you want to get just one string from your array, you could use Array#join, which is the opposite of String#split :
statement.join("\n")
It returns one string :
"Statement1\nStatement2"
when displayed with puts :
Statement1
Statement2
Your are trying call split method of Array class but Array class doesn't have this method.
You can check whether method is existed in calling class or not by using this way
statement = ["Statement1", "Statement2"]
statement.methods
[:inspect, :to_s, :to_a, :to_h, :to_ary, :frozen?, :==, :eql?, :hash, :[], :[]=, :at, :fetch, :first, :last, :concat, :<<, :push, :pop, :shift, :unshift, :insert, :each, :each_index, :reverse_each, :length, :size, :empty?, :find_index, :index, :rindex, :join, :reverse, :reverse!, :rotate, :rotate!, :sort, :sort!, :sort_by!, :collect, :collect!, :map, :map!, :select, :select!, :keep_if, :values_at, :delete, :delete_at, :delete_if, :reject, :reject!, :zip, :transpose, :replace, :clear, :fill, :include?, :<=>, :slice, :slice!, :assoc, :rassoc, :+, :*, :-, :&, :|, :uniq, :uniq!, :compact, :compact!, :flatten, :flatten!, :count, :shuffle!, :shuffle, :sample, :cycle, :permutation, :combination, :repeated_permutation, :repeated_combination, :product, :take, :take_while, :drop, :drop_while, :bsearch, :any?, :pack, :entries, :sort_by, :grep, :find, :detect, :find_all, :flat_map, :collect_concat, :inject, :reduce, :partition, :group_by, :all?, :one?, :none?, :min, :max, :minmax, :min_by, :max_by, :minmax_by, :member?, :each_with_index, :each_entry, :each_slice, :each_cons, :each_with_object, :chunk, :slice_before, :slice_after, :slice_when, :lazy, :nil?, :===, :=~, :!~, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :singleton_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
So there is no split method in this above response that's why your are getting this error.
So if you face any issue in future like this and it would help you.

Trouble highlighting in elasticsearch using rails

After reading several sites (including elasticsearch's documentation) and experimenting around a lot, I'm having trouble getting highlights. I can do the basic keyword search, but it's clear I'm not grasping something. Here's my code.
Gems:
gem 'elasticsearch-model'
gem 'elasticsearch-rails'
Controller:
class TermsController < ApplicationController
def search
#terms = Term.search(params[:query]).results
end
end
Model:
require 'elasticsearch/model'
class Term < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
settings index: { number_of_shards: 1, number_of_replicas: 0 } do
mappings dynamic: 'false' do
indexes :id, index: :not_analyzed
indexes :name, analyzer: 'spanish'
indexes :gender, index: :not_analyzed
indexes :part_of_speech, index: :not_analyzed
indexes :definition
indexes :etymology1
indexes :etymology2
indexes :uses
indexes :romance_cognates
indexes :notes1
indexes :notes2
indexes :quote1, analyzer: 'spanish'
indexes :quote2, analyzer: 'spanish'
end
end
def as_indexed_json(options = {})
as_json(
only: [:name, :gender, :part_of_speech, :definition, :etymology1, :etymology2, :uses, :romance_cognates, :notes1, :notes2, :quote1, :quote2]
)
end
def self.search(query)
__elasticsearch__.search(
{
query: {
multi_match: {
query: query,
fields: ['name', 'definition', 'etymology1', 'etymology2', 'uses', 'romance_cognates', 'notes1', 'notes2', 'quote1', 'quote2']
}
},
highlight: {
tags_schema: 'styled',
fields: {
:'*' => {}
}
}
}
)
end
end
# Delete the previous terms index in Elasticsearch
Term.__elasticsearch__.client.indices.delete index: Term.index_name rescue nil
# Create the new index with the new mapping
Term.__elasticsearch__.client.indices.create \
index: Term.index_name,
body: { settings: Term.settings.to_hash, mappings: Term.mappings.to_hash }
# Index all term records from the db to Elasticsearch
Term.import(force: true)
I also tried:
{
query: {
multi_match: {
query: query,
fields: ['name', 'definition', 'etymology1', 'etymology2', 'uses', 'romance_cognates', 'notes1', 'notes2', 'quote1', 'quote2']
}
},
highlight: {
fields: {
content: {'force_source': true}
}
}
}
and
{
query: {
multi_match: {
query: query,
fields: ['name', 'definition', 'etymology1', 'etymology2', 'uses', 'romance_cognates', 'notes1^5', 'notes2', 'quote1', 'quote2']
}
},
highlight: {
fields: {
content: {type: 'plain'}
}
}
}
and
{
query: {
multi_match: {
query: query,
fields: ['name', 'definition', 'etymology1', 'etymology2', 'uses', 'romance_cognates', 'notes1^5', 'notes2', 'quote1', 'quote2']
}
},
highlight: {
pre_tags: ['<tag1>']
post_tags: ['</tag1>']
fields: {
_all: {}
}
}
}
...Along with many other attempts I can't remember
It appears the key that I was missing as illustrated here is that I needed the try() method in my view template. I'm sure there's a more concise way of writing this, but a sample of my view syntax looks like this:
<%= term.try(:highlight).try(:definition) ? term.highlight.definition[0].html_safe : term.definition.html_safe %>
<%= term.try(:highlight).try(:etymology1) ? term.highlight.etymology1[0].html_safe : term.etymology1.html_safe %>

Rails Geocoder Testing with rspec

I am trying to set up my RSpec tests to use stubs rather then using networking to do the geocoding.
I added this:
before(:each) do
Geocoder.configure(:lookup => :test)
Geocoder::Lookup::Test.add_stub(
"Los Angeles, CA", [{
:latitude => 34.052363,
:longitude => -118.256551,
:address => 'Los Angeles, CA, USA',
:state => 'California',
:state_code => 'CA',
:country => 'United States',
:country_code => 'US'
}],
)
end
I am using FactoryGirl to create the test data like so:
FactoryGirl.define do
factory :market do
city 'Los Angeles'
state 'CA'
radius 20.0
end
end
The latitude/longitude are correctly being geocoded and stored in latitude/longitude. However, when I try:
Market.near(params[:search])
it returns nil.. But, if I just use the lookup => :google it works just as I intend it to. Has anyone got this working before, specifically the near method of geocoder?
I ended up coming back to this on a new project and figured it out.
The docs on geocoder actually state that the hash has to have string keys and not symbols. geocoder docs - see notes
i.e.
before(:each) do
Geocoder.configure(:lookup => :test)
Geocoder::Lookup::Test.add_stub(
"Los Angeles, CA", [{
"latitude" => 34.052363,
"longitude" => -118.256551,
"address" => 'Los Angeles, CA, USA',
"state" => 'California',
"state_code" => 'CA',
"country" => 'United States',
"country_code" => 'US'
}],
)
end
and not how I did it in the original post:
i.e. :latitude => 34.052363
I ended up doing something a bit more dynamic:
# frozen_string_literal: true
module GeocoderStub
def self.stub_with(facility)
Geocoder.configure(lookup: :test)
results = [
{
'latitude' => Faker::Address.latitude.first(9),
'longitude' => Faker::Address.longitude.first(9)
}
]
queries = [facility.full_address, facility.zip]
queries.each { |q| Geocoder::Lookup::Test.add_stub(q, results) }
end
end
and in my factory:
require './spec/support/geocoder_stub'
FactoryGirl.define do
factory :facility do
name { Faker::Company.name }
rating { rand(1..5) }
street { Faker::Address.street_address }
city { Faker::Address.city }
state { Faker::Address.state }
zip { Faker::Address.zip_code }
after(:build) { |facility| GeocoderStub.stub_with(facility) }
end
end
This adds a geocoder stub for every Facility factory that is built for both full address (method defined in facility) and zip.
I found a simpler approach to be just stubbing everything with the same values by default:
# test/test_helper.rb
Geocoder.configure(lookup: :test)
Geocoder::Lookup::Test.set_default_stub([{ coordinates: [40.7143528, -74.0059731] }])
Also, to avoid unnecessary calls, it's also a good idea to restrict your callbacks:
class Account < ActiveRecord
after_validation :geocode, if: ->(obj) { obj.address.present? and obj.address_changed? }
end
Source: https://github.com/alexreisner/geocoder#testing

Rails Elasticsearch-model model mapping - raw and not_analyzed

I am using the Elasticsearch-rails gem in my application. I need my index mapping in the model to look like the JSON you see below (shortened only to include only relevant pieces). The part I don't understand relates to "name." How would that mapping be setup if this is what I need it to look like?
JSON Mapping I want to Rails model to output
{
"recipes":{
"mappings":{
"list":{
"dynamic":"false",
"properties":{
"creator_name":{
"type":"string"
},
"name":{
"type":"string",
"fields":{
"raw":{
"type":"string",
"index":"not_analyzed"
}
}
},
"permalink":{
"type":"string"
},
"user_id":{
"type":"string"
}
}
}
}
}
}
Current Rails model mapping
settings :index => { :number_of_shards => 1 } do
mapping :dynamic => 'false' do
indexes :user_id, :type => 'string'
indexes :permalink, :type => 'string'
indexes :creator_name, :type => 'string'
indexes :name, :type => 'string' # How do i make this match the json?
end
end
How do I set indexing for 'name' in the model to look like the JSON?
Thanks a lot!

How to get tree data for self join model

I have model which place have many child places as bellow
class Place < ActiveRecord::Base
belongs_to :parent , class_name: "Place", foreign_key: "parent_id"
has_many :childs , class_name: "Place", foreign_key: "parent_id"
end
and i want to get data from this model in bellow form to represent in tree
data = [
{
label: 'place',
children: [
{ label: 'child1' , childern: [ {label: 'child11'} , {label: 'child12'}] },
{ label: 'child2' , childern: [ {label: 'child21'} , {label: 'child22'}] }
]
},
{
label: 'place',
children: [
{ label: 'child3' }
]
}
]
I started with this function
def get_tree(Place)
data = []
Place.all.each do |place|
dataInner= {label: place.name ,id: place.id}
children = [] # to hold childern data
place.childs.each do |child|
childhash = {label: child.name , id: child.id }
children.push(childhash)
end
dataInner.merge!(children: children) # push childern
data.push(dataInner)
end
return data
end
This function work ok but get depth 1 of childs only.
I want to get tree with any depth of childs
try something like
def get_tree(node)
return {label: node.name} if node.childs.empty?
{label: node.name, children: node.childs.collect { |v| get_tree(v) }
end

Resources